﻿using BarcodeLib;
using BarcodeLib.BarcodeXMLTableAdapters;
using Command;
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.ServiceModel.Configuration;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using U9BJWebApi.CheckLogin;
using U9BJWebApi.CreateCompRpt;
using U9BJWebApi.CreateRcvRptDoc;
using U9BJWebApi.CreateTransferIn;
using U9BJWebApi.ImportVoucherSv;
using U9BJWebApi.Models;
using U9BJWebApi.Models.RequestDTOs;
using U9BJWebApi.Models.ReturnDTOs;
using U9BJWebApi.Public;
using U9BJWebApi.SetUpASN;

namespace U9BJWebApi.Controllers
{
    public class AppController : ApiController
    {

        public static string ERPURL = System.Configuration.ConfigurationManager.AppSettings["ERPURL"].ToString();
        public static string enterpriseID = System.Configuration.ConfigurationManager.AppSettings["enterpriseID"].ToString();
        public static string connectionString = Decrypt(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString(), "ConnectionString");
        public static string PrinterName = System.Configuration.ConfigurationManager.AppSettings["PrinterName"].ToString();
        [HttpPost]
        public Result<BarCodeInfo> GetBarCodeInfo(BarCodeDTO dto)
        {
            Result<BarCodeInfo> rtn = new Result<BarCodeInfo>();




            DataSet barcodeds = DbHelperSQL.Query(@"select a.id,a.status, b.id itemid,b.name itemname,c.id lotid,c.Lotcode,d.id supid,d2.Name supname from Cust_BarCodeBE a 
													left join cbo_itemmaster  b on b.id = a.ItemMaster and b.org = " + dto.orgid + @"
													left join Lot_LotMaster c on c.id = a.Lot and c.item = b.id and c.usingorg = " + dto.orgid + @"
													left join CBO_Supplier d on d.id = a.Supplier and  d.org = " + dto.orgid + @"
													left join CBO_Supplier_Trl d2 on d2.id = a.Supplier
													left join PM_Receivement e on e.id = a.Receivement
													where  b.code = '" + dto.itemmastercode + "' and c.LotCode  " + (string.IsNullOrEmpty(dto.lotmastercode) ? "is null" : (" ='" + dto.lotmastercode + "'")) + " and d.code = '" + dto.suppliercode + "' and e.docno = '" + dto.Receivement + "' and  a.SerialNum =" + Convert.ToInt32(dto.SerialNum));

            if (barcodeds != null && barcodeds.Tables.Count > 0 && barcodeds.Tables[0].Rows.Count > 0)
            {
                if (Convert.ToInt32(barcodeds.Tables[0].Rows[0]["status"]) == 1)
                {
                    rtn.code = 0;
                    rtn.msg = "该条码已经被使用";
                    return rtn;
                }
                BarCodeInfo barCodeInfo = new BarCodeInfo();
                barCodeInfo.ItemMaster = Convert.ToInt64(barcodeds.Tables[0].Rows[0]["itemid"]);
                barCodeInfo.ItemMasterName = barcodeds.Tables[0].Rows[0]["itemname"].ToString();

                if (!string.IsNullOrEmpty(dto.lotmastercode))
                {
                    barCodeInfo.LotMaster = Convert.ToInt64(barcodeds.Tables[0].Rows[0]["lotid"]);
                    barCodeInfo.LotMasterCode = barcodeds.Tables[0].Rows[0]["Lotcode"].ToString();
                }
                barCodeInfo.Supplier = Convert.ToInt64(barcodeds.Tables[0].Rows[0]["supid"]);
                barCodeInfo.SupplierName = barcodeds.Tables[0].Rows[0]["supname"].ToString();
                barCodeInfo.Qty = dto.Qty;
                barCodeInfo.Receivement = dto.Receivement;
                barCodeInfo.SerialNum = dto.SerialNum;
                barCodeInfo.BarCodeID = barcodeds.Tables[0].Rows[0]["id"].ToString();

                rtn.data = barCodeInfo;
            }
            else
            {
                rtn.code = 0;
                rtn.msg = "找不到对应的条码";
                return rtn;
            }
            //DataSet ds = DbHelperSQL.Query(@"select id,name from cbo_itemmaster 
            //					where org = " + dto.orgid + " and code = '" + dto.itemmastercode + "'");


            //if (ds != null && ds.Tables.Count > 0)
            //{
            //	barCodeInfo.ItemMaster = Convert.ToInt64(ds.Tables[0].Rows[0]["id"]);
            //	barCodeInfo.ItemMasterName = ds.Tables[0].Rows[0]["name"].ToString();

            //	DataSet ds2 = DbHelperSQL.Query(@"select id,Lotcode from Lot_LotMaster 
            //						where usingorg = " + dto.orgid + " and Lotcode = '" + dto.lotmastercode + "' " +
            //						"and item =" + barCodeInfo.ItemMaster);
            //	if (ds2 != null && ds2.Tables.Count > 0&& ds2.Tables[0].Rows.Count > 0)
            //	{
            //		barCodeInfo.LotMaster = Convert.ToInt64(ds2.Tables[0].Rows[0]["id"]);
            //		barCodeInfo.LotMasterCode =ds2.Tables[0].Rows[0]["Lotcode"].ToString();
            //	}
            //	else 
            //	{
            //		rtn.code = 0;
            //		rtn.msg = "找不到对应的批号";
            //		return rtn;
            //	}

            //	DataSet ds3 = DbHelperSQL.Query(@"select m.id,l.name from CBO_Supplier m
            //						left join CBO_Supplier_Trl l on m.id=l.id
            //						where m.org = " + dto.orgid + " and m.code = '" + dto.suppliercode + "'");
            //	if (ds3 != null && ds3.Tables.Count > 0)
            //	{
            //		barCodeInfo.Supplier = Convert.ToInt64(ds3.Tables[0].Rows[0]["id"]);
            //		barCodeInfo.SupplierName = ds3.Tables[0].Rows[0]["name"].ToString();
            //	}
            //	else
            //	{
            //		rtn.code = 0;
            //		rtn.msg = "找不到对应的供应商";
            //		return rtn;
            //	}
            //	rtn.data = barCodeInfo;
            //}
            //else
            //{
            //	rtn.code = 0;
            //	rtn.msg = "找不到对应的物料";
            //}

            return rtn;
        }

        [HttpGet]
        public Result<List<Warehouse>> Warehouselist(string code)
        {
            DataSet ds = DbHelperSQL.Query($@"
select m.ID,t.Name,m.Code
from CBO_Wh m
left join CBO_Wh_trl t on m.id = t.id
where Effective_IsEffective = 1 and m.org = {code}
order by m.Manager,t.Name");
            List<Warehouse> DTOs = new List<Warehouse>();
            if (ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Warehouse dto = new Warehouse();
                        dto.id = Convert.ToInt64(dt.Rows[i]["ID"]);
                        dto.Name = dt.Rows[i]["Name"].ToString();
                        dto.Code = dt.Rows[i]["Code"].ToString();

                        DTOs.Add(dto);
                    }

                }
            }
            Result<List<Warehouse>> rtn = new Result<List<Warehouse>>();
            rtn.data = DTOs;
            return rtn;
        }
        [HttpGet]
        public Result<List<Warehouse>> Warehouselist1(string code)
        {
            DataSet ds = DbHelperSQL.Query($@"
select m.ID,t.Name,m.Code
from CBO_Wh m
inner join Base_Organization org on m.org = org.ID
left join CBO_Wh_trl t on m.id = t.id
where m.Effective_IsEffective = 1 and org.Code = '{code}'
order by m.Manager,t.Name");
            List<Warehouse> DTOs = new List<Warehouse>();
            if (ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Warehouse dto = new Warehouse();
                        dto.id = Convert.ToInt64(dt.Rows[i]["ID"]);
                        dto.Name = dt.Rows[i]["Name"].ToString();
                        dto.Code = dt.Rows[i]["Code"].ToString();

                        DTOs.Add(dto);
                    }

                }
            }
            Result<List<Warehouse>> rtn = new Result<List<Warehouse>>();
            rtn.data = DTOs;
            return rtn;
        }
        [HttpGet]
        public Result<List<Organization>> OrganizationList()
        {
            DataSet ds = DbHelperSQL.Query(@"select m.ID,t.Name,m.Code from Base_Organization m
								left join Base_Organization_trl t on m.id = t.id
								where m.isoperatingorg = 1");
            List<Organization> DTOs = new List<Organization>();
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Organization dto = new Organization();
                        dto.ID = Convert.ToInt64(dt.Rows[i]["ID"]);
                        dto.Name = dt.Rows[i]["Code"].ToString() + "-" + dt.Rows[i]["Name"].ToString();
                        dto.Code = dt.Rows[i]["Code"].ToString();

                        DTOs.Add(dto);
                    }

                }
            }
            Result<List<Organization>> rtn = new Result<List<Organization>>();
            rtn.data = DTOs;
            return rtn;
        }


        /// <summary>
        /// 实例化上下文对象
        /// </summary>
        /// <returns></returns>
        public static CheckLogin.ThreadContext CreateContext(long orgID, long userId, string enterpriseID)
        {
            //实例化上下文对象
            CheckLogin.ThreadContext context = new CheckLogin.ThreadContext();

            CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[] av = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[7];

            av[0] = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[0].Key = "OrgID";                        //组织
            av[0].Value = orgID;

            av[1] = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[1].Key = "UserID";                       //用户
            av[1].Value = userId;

            av[2] = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[2].Key = "CultureName";                  //语言
            av[2].Value = "zh-CN";

            av[3] = new CheckLogin.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[3].Key = "EnterpriseID";                 //企业
            av[3].Value = enterpriseID;

            //av[4] = new ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            //av[4].Key = "DefaultCultureName";           //默认语言
            //av[4].Value = PubClass.Culture;

            //av[5] = new ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            //av[5].Key = "EnterpriseName";               //企业名称
            //av[5].Value = PubClass.EnterpriseName;

            //av[6] = new ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            //av[6].Key = "Support_CultureNameList";      //语言
            //av[6].Value = PubClass.Culture;

            context.nameValueHas = av;

            return context;
        }


        /// <summary>
        /// 实例化上下文对象
        /// </summary>
        /// <returns></returns>
        public static TransferIn.ThreadContext CreateContextTransferIn(long orgID, long userId, string enterpriseID, string OrgCode)
        {
            //实例化上下文对象
            TransferIn.ThreadContext context = new TransferIn.ThreadContext();

            TransferIn.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[] av = new TransferIn.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[7];

            av[0] = new TransferIn.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[0].Key = "OrgID";                        //组织
            av[0].Value = orgID;

            av[1] = new TransferIn.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[1].Key = "UserID";                       //用户
            av[1].Value = userId;

            av[2] = new TransferIn.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[2].Key = "CultureName";                  //语言
            av[2].Value = "zh-CN";

            av[3] = new TransferIn.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[3].Key = "EnterpriseID";                 //企业
            av[3].Value = enterpriseID;

            av[4] = new TransferIn.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[4].Key = "DefaultCultureName";           //默认语言
            av[4].Value = "zh-CN";

            av[5] = new TransferIn.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[5].Key = "EnterpriseName";               //企业名称
            av[5].Value = OrgCode;

            av[6] = new TransferIn.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[6].Key = "Support_CultureNameList";      //语言
            av[6].Value = "zh-CN";

            context.nameValueHas = av;

            return context;
        }


        /// <summary>
        /// 实例化上下文对象
        /// </summary>
        /// <returns></returns>
        public static RcvByASN.ThreadContext CreateContextASN(long orgID, long userId, string enterpriseID, string orgCode)
        {
            //实例化上下文对象
            RcvByASN.ThreadContext context = new RcvByASN.ThreadContext();

            RcvByASN.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[] av = new RcvByASN.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[7];

            av[0] = new RcvByASN.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[0].Key = "OrgID";                        //组织
            av[0].Value = orgID;

            av[1] = new RcvByASN.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[1].Key = "UserID";                       //用户
            av[1].Value = userId;

            av[2] = new RcvByASN.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[2].Key = "CultureName";                  //语言
            av[2].Value = "zh-CN";

            av[3] = new RcvByASN.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[3].Key = "EnterpriseID";                 //企业
            av[3].Value = enterpriseID;

            av[4] = new RcvByASN.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[4].Key = "DefaultCultureName";           //默认语言
            av[4].Value = "zh-CN";

            av[5] = new RcvByASN.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[5].Key = "EnterpriseName";               //企业名称
            av[5].Value = orgCode;

            av[6] = new RcvByASN.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[6].Key = "Support_CultureNameList";      //语言
            av[6].Value = "zh-CN";

            context.nameValueHas = av;

            return context;
        }

        /// <summary>
        /// 实例化上下文对象
        /// </summary>
        /// <returns></returns>
        public static CloseAsnLine.ThreadContext CreateContextCloseASNLine(long orgID, long userId, string enterpriseID, string OrgCode)
        {
            //实例化上下文对象
            CloseAsnLine.ThreadContext context = new CloseAsnLine.ThreadContext();

            CloseAsnLine.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[] av = new CloseAsnLine.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[7];

            av[0] = new CloseAsnLine.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[0].Key = "OrgID";                        //组织
            av[0].Value = orgID;

            av[1] = new CloseAsnLine.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[1].Key = "UserID";                       //用户
            av[1].Value = userId;

            av[2] = new CloseAsnLine.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[2].Key = "CultureName";                  //语言
            av[2].Value = "zh-CN";

            av[3] = new CloseAsnLine.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[3].Key = "EnterpriseID";                 //企业
            av[3].Value = enterpriseID;


            av[4] = new CloseAsnLine.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[4].Key = "DefaultCultureName";           //默认语言
            av[4].Value = "zh-CN";

            av[5] = new CloseAsnLine.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[5].Key = "EnterpriseName";               //企业名称
            av[5].Value = OrgCode;

            av[6] = new CloseAsnLine.ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType();
            av[6].Key = "Support_CultureNameList";      //语言
            av[6].Value = "zh-CN";

            context.nameValueHas = av;

            return context;
        }

        public static T CreateContext<T>(long orgID, long userId, string enterpriseID, string orgCode) where T : new()
        {
            T context = new T();
            Type type = typeof(T);
            var prop = type.GetProperty("nameValueHas");
            var avList = Array.CreateInstance(prop.PropertyType.GetElementType(), 7);

            var avType = prop.PropertyType.GetElementType();
            var av1 = avType.Assembly.CreateInstance(avType.FullName);
            avType.GetProperty("Key").SetValue(av1, "OrgID", null);
            avType.GetProperty("Value").SetValue(av1, orgID, null);
            avList.SetValue(av1, 0);

            var av2 = avType.Assembly.CreateInstance(avType.FullName);
            avType.GetProperty("Key").SetValue(av2, "UserID", null);
            avType.GetProperty("Value").SetValue(av2, userId, null);
            avList.SetValue(av2, 1);

            var av3 = avType.Assembly.CreateInstance(avType.FullName);
            avType.GetProperty("Key").SetValue(av3, "CultureName", null);
            avType.GetProperty("Value").SetValue(av3, "zh-CN", null);
            avList.SetValue(av3, 2);

            var av4 = avType.Assembly.CreateInstance(avType.FullName);
            avType.GetProperty("Key").SetValue(av4, "EnterpriseID", null);
            avType.GetProperty("Value").SetValue(av4, enterpriseID, null);
            avList.SetValue(av4, 3);

            var av5 = avType.Assembly.CreateInstance(avType.FullName);
            avType.GetProperty("Key").SetValue(av5, "DefaultCultureName", null);
            avType.GetProperty("Value").SetValue(av5, "zh-CN", null);
            avList.SetValue(av5, 4);

            var av6 = avType.Assembly.CreateInstance(avType.FullName);
            avType.GetProperty("Key").SetValue(av6, "EnterpriseName", null);
            avType.GetProperty("Value").SetValue(av6, orgCode, null);
            avList.SetValue(av6, 5);


            var av7 = avType.Assembly.CreateInstance(avType.FullName);
            avType.GetProperty("Key").SetValue(av7, "Support_CultureNameList", null);
            avType.GetProperty("Value").SetValue(av7, "zh-CN", null);
            avList.SetValue(av7, 6);

            prop.SetValue(context, avList, null);
            return context;
        }


        /// <summary>
        /// 检查登陆
        /// </summary>
        /// <returns></returns>
        public static UFIDACUSTHXBMBMSVLoginInfoDTOData CheckLogin(long orgID, long userId, string userCode, string passward, string url, string enterpriseID)
        {
            CheckLoginSVStub login = new CheckLoginSVStub();

            UFIDACUSTHXBMBMSVLoginInfoDTOData info = new UFIDACUSTHXBMBMSVLoginInfoDTOData();

            //传入URL、设定时间
            login.Url = url;
            //给上下文信息赋值
            //实例化上下文对象
            CheckLogin.ThreadContext context = CreateContext(orgID, userId, enterpriseID);

            //给出入参数赋值
            info.m_userCode = userCode;
            info.m_passward = passward;
            info.m_orgID = orgID.ToString();
            info.m_languageID = "1002006072100009";
            info.m_iP = "192.168.125.84";
            info.m_enterpriseId = enterpriseID;


            info = login.Do(context, info, out CheckLogin.MessageBase[] messageBase);
            return info;
        }


        [HttpPost]
        public Result<LoginInfo> Login(ReciveData data)
        {
            Result<LoginInfo> rtn = new Result<LoginInfo>();

            var dto = JsonConvert.DeserializeObject<LoginDto>(data.dtoJsonStr);
            DataSet ds = DbHelperSQL.Query(@"select id from base_user where code = '" + data.userNo + "'");
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                var UserId = ds.Tables[0].Rows[0]["id"].ToString();
                try
                {
                    byte[] array = new UnicodeEncoding().GetBytes(dto.UserPwd);
                    array = MD5.Create().ComputeHash(array);
                    var PW = Convert.ToBase64String(array);
                    //账号密码验证
                    string pwsql = $"select Name from Base_User WHERE code='{dto.UserNo}' and password=upper(substring(sys.fn_VarBinToHexStr(hashbytes('MD5', CAST('{PW}' as varchar(50)) + convert(char(36),base_user.salt))),3,32))";
                    DataSet pwDS = DbHelperSQL.Query(pwsql);
                    if (pwDS.Tables[0].Rows.Count == 0)
                    {
                        rtn.code = 0;
                        rtn.msg = "用户名或密码错误";
                        return rtn;
                    }
                    bool IsActive = UserActiveCheck(Convert.ToInt64(UserId));
                    if (!IsActive)
                    {
                        rtn.msg = "当前登录用户不是有效的用户";
                        rtn.code = 0;
                        return rtn;
                    }
                    var loginIP = HttpContext.Current.Request.UserHostAddress;
                    //插入登录记录
                    var guid = GuidToLongID();
                    var loginSql = $@"INSERT INTO [dbo].[UBF_Log_OperateLog]([CreatedOn],[ModifiedOn],[OccurrenceTime],[IsSuccess],[ActionType],[CreatedBy],[ModifiedBy],[MachineIP],[Menu],[Form],[ErrorMessage],
[SessionID],[Description],[Org],[Application],[ID],[SysVersion],[LoginUser])
VALUES(getdate(),getdate(),getdate(),1,2,'PDA','PDA','{loginIP}','00000000-0000-0000-0000-000000000000','00000000-0000-0000-0000-000000000000','','PDA',''
,{data.factoryId},-1,{guid},0,{Convert.ToInt64(UserId)})
INSERT INTO UBF_Log_OperateLog_Trl values({guid},'zh-CN','登录')";
                    DbHelperSQL.ExecuteSql(loginSql);
                    LoginInfo loginInfo = new LoginInfo();
                    loginInfo.username = dto.UserNo;
                    loginInfo.password = dto.UserPwd;
                    loginInfo.factoryId = data.factoryId;
                    loginInfo.userId = Convert.ToInt64(UserId);
                    rtn.data = loginInfo;

                    return rtn;

                }
                catch (System.Exception ex)
                {
                    rtn.msg = ex.Message.ToString();
                    rtn.code = 0;
                    return rtn;
                }
            }
            else
            {
                rtn.msg = "登录失败，未找到账号，请检查是否输入错误或联系管理员";
                rtn.code = 0;
                return rtn;
            }

            //DataSet ds = DbHelperSQL.Query(@"select id from base_user where code = '" + data.userNo + "'");
            //if (ds != null && ds.Tables.Count > 0)
            //{
            //	var UserId = ds.Tables[0].Rows[0]["id"].ToString();


            //	LoginInfo loginInfo = new LoginInfo();
            //	loginInfo.username = dto.UserNo;
            //	loginInfo.password = dto.UserPwd;
            //	loginInfo.factoryId = data.factoryId;
            //	loginInfo.userId = Convert.ToInt64(UserId);
            //	rtn.data = loginInfo;
            //}

            //return rtn;




            //if (MD5PWD == password2)
            //{
            //	rtn.msg = "登陆成功";
            //	LoginInfo loginInfo = new LoginInfo();
            //	loginInfo.username = ds.Tables[0].Rows[0]["code"].ToString();
            //	loginInfo.password = dto.UserPwd;
            //	loginInfo.factoryId = data.factoryId;
            //	rtn.data = loginInfo;
            //}
            //else
            //{
            //	rtn.code = 0;
            //	rtn.msg = "登陆失败";
            //}
        }

        [HttpPost]
        public Result<PullListRTNDTO> PullListInfo(PullListInfoDTO data)
        {
            DataSet ds = DbHelperSQL.Query(@"select DocState from MO_PullList where docno = '" + data.pulllistcode + "' and org = " + data.org);
            Result<PullListRTNDTO> rtn = new Result<PullListRTNDTO>();
            PullListRTNDTO pullListRTNDTO = new PullListRTNDTO();

            if (ds != null && ds.Tables.Count > 0)
            {
                var DocState = ds.Tables[0].Rows[0]["DocState"].ToString();
                if (DocState != "2")
                {
                    rtn.code = 0;
                    rtn.msg = "该拣货单不是审核通过状态";
                    return rtn;
                }
                DataSet ds2 = DbHelperSQL.Query(@"select pld.PullList,pld.Id AS PullListDemandLine,pld.ItemMaster,it.NameCombineName as ItemMasterName,itm.code as ItemMasterCode,pld.demandqty as RequireQty, pld.totalissuedqty,wh.name as warehouse ,wh.Id as warehouseId
									from MO_PullListDemandLine pld
									left join CBO_ItemMaster_Trl it on it.id = pld.ItemMaster 
									left join CBO_ItemMaster itm on itm.id = it.id 
									left join CBO_Wh_Trl wh on wh.id = pld.towarehouse 
									left join MO_PullList pl on pl.id = pld.pulllist
									where pld.demandqty > pld.totalissuedqty
									and pl.docno = '" + data.pulllistcode + "' and  itm.DescFlexField_PrivateDescSeg4 = '" + data.user + "' and itm.org = " + data.org);

                if (ds2 != null && ds2.Tables.Count > 0)
                {
                    DataTable dt = ds2.Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        pullListRTNDTO.warehouse = dt.Rows[0]["warehouse"].ToString();
                        pullListRTNDTO.warehouseId = dt.Rows[0]["warehouseId"].ToString();
                        pullListRTNDTO.PullLists = new List<PullListDTO>();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {


                            PullListDTO pullListDTO = new PullListDTO();
                            pullListDTO.PullList = Convert.ToInt64(dt.Rows[i]["PullList"]);
                            pullListDTO.PullListDemandLine = Convert.ToInt64(dt.Rows[i]["PullListDemandLine"]);
                            pullListDTO.ItemMaster = Convert.ToInt64(dt.Rows[i]["ItemMaster"]);
                            pullListDTO.ItemMasterName = dt.Rows[i]["ItemMasterName"].ToString();
                            pullListDTO.ItemMasterCode = dt.Rows[i]["ItemMasterCode"].ToString();
                            pullListDTO.RequireQty = Convert.ToDecimal(dt.Rows[i]["RequireQty"]);
                            pullListDTO.TotalIssuedQty = Convert.ToDecimal(dt.Rows[i]["TotalIssuedQty"]);

                            pullListRTNDTO.PullLists.Add(pullListDTO);

                        }
                    }

                }
                rtn.data = pullListRTNDTO;
                return rtn;
            }
            rtn.code = 0;
            rtn.msg = "未找到该拣货单";
            return rtn;

        }


        [HttpPost]
        public Result<ASNRTNDTO> getASNInfo(ASNInfoDTO data)
        {
            string ASNCode = data.ASNCode.Contains("|") ? data.ASNCode.Split('|')[4] : data.ASNCode;
            string ItemCode = data.ASNCode.Contains("|") ? data.ASNCode.Split('|')[0] : "";
            DataSet ds = DbHelperSQL.Query(@"select Status from PM_ASN where docno = '" + ASNCode + "' and org = " + data.org);
            Result<ASNRTNDTO> rtn = new Result<ASNRTNDTO>();
            ASNRTNDTO ASNRTNDTO = new ASNRTNDTO();

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                var Status = ds.Tables[0].Rows[0]["Status"].ToString();
                if (Status != "2")
                {
                    rtn.code = 0;
                    rtn.msg = "该ASN单不是已审核状态";
                    return rtn;
                }
                DataSet ds2 = DbHelperSQL.Query($@"select M.ID AS ASNID,l.id as asnlineid,m.supplier_supplier as supplierId,s.Name AS supplierName,m.docno,
									l.SrcDocInfo_SrcDocNo as purchaseorder,l.doclineno as asnLineno,l.ItemInfo_ItemID as ItemMaster,l.ItemInfo_ItemCode as itemCode ,l.ItemInfo_ItemName as itemName,l.ShipQtyTU as arrivalQty,wh.name as wh,whm.code as whcode,bin.name as bin,binm.code as bincode
									from PM_ASN m
									left join PM_ASNLine l on m.id = l.asn
									left join CBO_ItemMaster it on it.id = l.ItemInfo_ItemID
									left join CBO_InventoryInfo iv on iv.ItemMaster = it.id
									left join cbo_wh_trl wh on wh.id = iv.Warehouse 
									left join cbo_wh whm on whm.id = wh.id
									left join cbo_bin_trl  bin on bin.id = iv.bin
									left join cbo_bin  binm on binm.id = bin.id
									left join CBO_InventoryInfo ii on ii.id = it.InventoryInfo
									left join CBO_Supplier_trl s on m.Supplier_Supplier = s.id
									left join CBO_Operators op on op.id = ii.WarehouseManager
									where m.docno = '{ASNCode}' and l.Status = 2" + (string.IsNullOrEmpty(ItemCode) ? "" : $" and it.Code = '{ItemCode}'"));
                //DataSet ds2 = DbHelperSQL.Query(@"select M.ID AS ASNID,l.id as asnlineid,m.supplier_supplier as supplierId,m.supplier_shortname AS supplierName,m.docno,
                //					l.SrcDocInfo_SrcDocNo as purchaseorder,l.doclineno as asnLineno,l.ItemInfo_ItemID as ItemMaster,l.ItemInfo_ItemCode as itemCode ,l.ItemInfo_ItemName as itemName,l.ShipQtyTU as arrivalQty,wh.name as wh,whm.code as whcode,bin.name as bin,binm.code as bincode
                //					from PM_ASN m
                //					left join PM_ASNLine l on m.id = l.asn
                //					left join CBO_ItemMaster it on it.id = l.ItemInfo_ItemID
                //					left join CBO_InventoryInfo iv on iv.ItemMaster = it.id
                //					left join cbo_wh_trl wh on wh.id = iv.Warehouse 
                //					left join cbo_wh whm on whm.id = wh.id
                //					left join	cbo_bin_trl  bin on bin.id = iv.bin
                //					left join	cbo_bin  binm on binm.id = bin.id								
                //					where m.docno = '" + data.ASNCode + "' and it.DescFlexField_PrivateDescSeg7 = '" + data.user + "' and l.Status = 2");

                if (ds2 != null && ds2.Tables.Count > 0)
                {
                    DataTable dt = ds2.Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        ASNRTNDTO.asnId = Convert.ToInt64(dt.Rows[0]["ASNID"]);
                        ASNRTNDTO.supplierId = dt.Rows[0]["supplierId"].ToString();
                        ASNRTNDTO.supplierName = dt.Rows[0]["supplierName"].ToString();
                        ASNRTNDTO.detailList = new List<ASNDTO>();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {


                            ASNDTO ASNDTO = new ASNDTO();
                            ASNDTO.ASNID = Convert.ToInt64(dt.Rows[i]["ASNID"]);
                            ASNDTO.asnlineid = Convert.ToInt64(dt.Rows[i]["asnlineid"]);
                            ASNDTO.purchaseorder = dt.Rows[i]["purchaseorder"].ToString();
                            ASNDTO.asnLineno = dt.Rows[i]["asnLineno"].ToString();
                            ASNDTO.ItemMaster = Convert.ToInt64(dt.Rows[i]["ItemMaster"]);
                            ASNDTO.itemCode = dt.Rows[i]["itemCode"].ToString();
                            ASNDTO.itemName = dt.Rows[i]["itemName"].ToString();
                            ASNDTO.arrivalQty = Convert.ToDecimal(dt.Rows[i]["arrivalQty"]);
                            ASNDTO.qualifiyQty = Convert.ToDecimal(dt.Rows[i]["arrivalQty"]);
                            ASNDTO.unqualifiyQty = 0;
                            ASNDTO.whcode = dt.Rows[i]["whcode"].ToString();
                            ASNDTO.wh = dt.Rows[i]["wh"].ToString();
                            if (!string.IsNullOrEmpty(dt.Rows[i]["bincode"].ToString()))
                            {
                                ASNDTO.bincode = dt.Rows[i]["bincode"].ToString();
                                ASNDTO.bin = dt.Rows[i]["bin"].ToString();
                            }


                            ASNRTNDTO.detailList.Add(ASNDTO);

                        }
                    }

                }
                rtn.data = ASNRTNDTO;
                return rtn;
            }
            rtn.code = 0;
            rtn.msg = "未找到该ASN单";
            return rtn;

        }


        [HttpPost]
        public Result<string> PostPullListInfo(PullListReciveDTO data)
        {
            Result<string> rtn = new Result<string>();
            //List<PullListDTO> dtos = new List<PullListDTO>();
            if (data.list.Count > 0)
            {
                TransferIn.OneTransferInServiceStub TransferIn = new TransferIn.OneTransferInServiceStub();
                TransferIn.MessageBase[] messageBase = null;
                TransferIn.Url = ERPURL + "/U9/Services/UFIDA.CUST.HX.BM.BMSV.IOneTransferInService.svc?wsdl";
                DataSet Orgds = DbHelperSQL.Query(@"select code from Base_Organization where Id = " + data.org);

                var OrgCode = Orgds.Tables[0].Rows[0]["code"].ToString();


                TransferIn.ThreadContext context = CreateContextTransferIn(data.org, data.userId, enterpriseID, OrgCode);

                DataSet ds = DbHelperSQL.Query(@"select id from InvDoc_TransInDocType where org = " + data.org + "  and Code = 'TransIn002'");

                var Doctype = ds.Tables[0].Rows[0]["id"].ToString();

                TransferIn.UFIDACUSTHXBMBMSVTransferPDALineDTOData[] PDALines = new TransferIn.UFIDACUSTHXBMBMSVTransferPDALineDTOData[data.list.Count];

                List<PullListDTO> dtos = new List<PullListDTO>();

                string barcodeids = "";
                for (var i = 0; i < data.list.Count; i++)
                {

                    PullListDTO dto = JsonConvert.DeserializeObject<PullListDTO>(data.list[i]);

                    PDALines[i] = new TransferIn.UFIDACUSTHXBMBMSVTransferPDALineDTOData();
                    PDALines[i].m_org = data.org.ToString();
                    PDALines[i].m_outWarehouse = data.Warehouse;
                    PDALines[i].m_inWarehouse = data.TargetWarehouse;
                    PDALines[i].m_itemID = dto.ItemMaster.ToString();
                    PDALines[i].m_itemName = dto.ItemMasterName;
                    PDALines[i].m_itemCode = dto.ItemMasterCode;
                    PDALines[i].m_num = Convert.ToInt32(dto.Qty);
                    PDALines[i].m_pDALineNo = (i + 1) * 10;
                    PDALines[i].m_inOrg = data.org.ToString();
                    PDALines[i].m_outOrg = data.org.ToString();
                    PDALines[i].m_inNum = dto.Qty.ToString();
                    PDALines[i].m_docTypeID = Doctype;
                    PDALines[i].m_productcode = dto.LotMasterCode == null ? "" : dto.LotMasterCode;
                    PDALines[i].m_createdBy = data.userName;
                    dtos.Add(dto);
                    //PDALines[i].= dto.bin

                    if (!string.IsNullOrEmpty(dto.UsedBarCode))
                    {
                        barcodeids += (dto.UsedBarCode + ",");
                    }

                }
                try
                {
                    TransferIn.UFIDACUSTHXBMBMSVRusultDTOData[] rt = TransferIn.Do(context, PDALines, out messageBase);

                    var flg = true;

                    foreach (var item in rt)
                    {
                        if (!string.IsNullOrEmpty(item.m_result) && !item.m_result.Contains("成功"))
                        {
                            flg = false;
                            rtn.msg += (item.m_result + ";");
                        }

                    }
                    if (flg)
                    {
                        rtn.msg = "拣货成功";

                        if (!string.IsNullOrEmpty(barcodeids))
                        {
                            string sql = @"update Cust_BarCodeBE set status = 1 where  id  in (" + barcodeids.TrimEnd(',') + ")";
                            DbHelperSQL.ExecuteSql(sql);
                        }

                        //回写补货需求单
                        foreach (var dto in dtos)
                        {

                            string sql = @"update MO_PullListDemandLine set TotalIssuedQty = (TotalIssuedQty + " + dto.Qty + ") where  id = " + dto.PullListDemandLine;
                            DbHelperSQL.ExecuteSql(sql);


                        }

                        //检测是否关闭
                        DataSet ckds = DbHelperSQL.Query(@"select count(*) count from  mo_PullListDemandLine l
													left join  mo_PullList m on l.PullList = m.id
													left join cbo_itemmaster i on i.id = l.ItemMaster
													where i.DescFlexField_PrivateDescSeg4 != 'True' and l.TotalIssuedQty<l.DemandQty and m.Id = " + dtos.FirstOrDefault().PullList);

                        var count = ckds.Tables[0].Rows[0]["count"].ToString();
                        if (Convert.ToInt32(count) == 0)
                        {
                            string sql = @"update mo_PullList set DocState = 3  where  id = " + dtos.FirstOrDefault().PullList;
                            DbHelperSQL.ExecuteSql(sql);
                        }
                        return rtn;
                    }
                    else
                    {
                        rtn.code = 0;
                        return rtn;
                    }
                }
                catch (System.Exception e)
                {
                    rtn.code = 0;
                    rtn.msg = e.Message;
                    return rtn;
                }
            }
            else
            {
                rtn.code = 0;
                rtn.msg = "请选择拣货行";
                return rtn;
            }


        }



        [HttpPost]
        public Result<List<string>> postASNLineInfo(ASNLineListReciveDTO data)
        {
            Result<List<string>> rtn = new Result<List<string>>();

            //List<PullListDTO> dtos = new List<PullListDTO>();
            if (data.list.Count > 0)
            {
                RcvByASN.CreateRcvByASNSVStub Rcv = new RcvByASN.CreateRcvByASNSVStub();
                RcvByASN.MessageBase[] messageBase = null;

                DataSet Doctypeds = DbHelperSQL.Query(@"select id from PM_RcvDocType where org = " + data.org + "  and Code = 'RCV01'");

                var Doctype = Doctypeds.Tables[0].Rows[0]["id"].ToString();

                //DataSet Orgds = DbHelperSQL.Query(@"select code from Base_Organization where Id = " + data.org);
                var ContextCode = PublicMethod.CheckContext(data.org, data.userId);
                var OrgCode = ContextCode.OrgCode;


                //传入URL、设定时间
                Rcv.Url = ERPURL + "/u9/Services/UFIDA.CUST.HX.BM.BMSV.ICreateRcvByASNSV.svc?wsdl";
                //给上下文信息赋值
                //实例化上下文对象
                RcvByASN.ThreadContext context = CreateContextASN(data.org, data.userId, enterpriseID, OrgCode);

                RcvByASN.UFIDACUSTHXBMBMSVASNRcvDtoData PDADto = new RcvByASN.UFIDACUSTHXBMBMSVASNRcvDtoData();

                PDADto.m_orgCode = OrgCode;
                PDADto.m_asnRcvLineInfos = new RcvByASN.UFIDACUSTHXBMBMSVASNRcvLineDtoData[data.list.Count];
                PDADto.m_mesDocNo = "11";
                PDADto.m_createdBy = ContextCode.UserName;
                PDADto.m_createdOn = data.BusinessDate;
                PDADto.m_createdOnSpecified = true;
                List<ASNDTO> dtos = new List<ASNDTO>();
                for (var i = 0; i < data.list.Count; i++)
                {

                    ASNDTO dto = JsonConvert.DeserializeObject<ASNDTO>(data.list[i]);

                    //DataSet ds2 = DbHelperSQL.Query(@"select SrcDocInfo_SrcDoc_EntityID poid,SrcDocInfo_SrcDocLine_EntityID polineid ,SrcDocInfo_SrcDocLineNo polineno from PM_ASNLine where id =" + dto.asnlineid);
                    //var poid = ds2.Tables[0].Rows[0]["poid"].ToString();
                    //var polineid = ds2.Tables[0].Rows[0]["polineid"].ToString();
                    //var polineno = ds2.Tables[0].Rows[0]["polineno"].ToString();


                    PDADto.m_asnRcvLineInfos[i] = new RcvByASN.UFIDACUSTHXBMBMSVASNRcvLineDtoData();

                    PDADto.m_asnRcvLineInfos[i].m_aSNDocNo = data.asnDocNo;
                    PDADto.m_asnRcvLineInfos[i].m_aSNLineID = dto.asnlineid.ToString();
                    PDADto.m_asnRcvLineInfos[i].m_aSNDocLine = dto.asnLineno;
                    PDADto.m_asnRcvLineInfos[i].m_itemCode = dto.itemCode;
                    PDADto.m_asnRcvLineInfos[i].m_rcvQty = dto.qualifiyQty.ToString();
                    PDADto.m_asnRcvLineInfos[i].m_whCode = dto.whcode;
                    PDADto.m_asnRcvLineInfos[i].m_mesDocLineNo = "11";



                    PDADto.m_asnRcvLineInfos[i].m_asnRcvSubLines = new RcvByASN.UFIDACUSTHXBMBMSVASNRcvSubLineDtoData[] { new RcvByASN.UFIDACUSTHXBMBMSVASNRcvSubLineDtoData() };

                    PDADto.m_asnRcvLineInfos[i].m_asnRcvSubLines[0].m_binCode = dto.bincode;
                    PDADto.m_asnRcvLineInfos[i].m_asnRcvSubLines[0].m_qty = dto.qualifiyQty.ToString();
                    //PDADto.m_asnRcvLineInfos[i].m_asnRcvSubLines[0].m_sNList

                    dtos.Add(dto);
                }

                try
                {
                    RcvByASN.UFIDACUSTHXBMBMSVRusultDTOData rt = Rcv.Do(context, PDADto, "", out messageBase);


                    if (!string.IsNullOrEmpty(rt.m_result) && rt.m_result.Contains("失败"))
                    {
                        rtn.code = 0;
                        rtn.msg = rt.m_result;
                        return rtn;

                    }
                    else
                    {
                        List<ASNDTO> dtos2 = new List<ASNDTO>();
                        foreach (var dto in dtos)
                        {
                            DataSet asnlineckds = DbHelperSQL.Query(@"select Status from PM_ASNLine where Id = " + dto.asnlineid);

                            var asnlinestatus = asnlineckds.Tables[0].Rows[0]["Status"].ToString();
                            if (asnlinestatus == "2")
                            {
                                dtos2.Add(dto);
                            }
                        }
                        if (dtos2.Count > 0)
                        {
                            CloseAsnLine.CloseASNLineSVStub closeASNLine = new CloseAsnLine.CloseASNLineSVStub();

                            //传入URL、设定时间
                            closeASNLine.Url = ERPURL + "/u9/Services/UFIDA.U9.PM.PO.ICloseASNLineSV.svc?wsdl";
                            //给上下文信息赋值
                            //实例化上下文对象
                            CloseAsnLine.ThreadContext context2 = CreateContextCloseASNLine(data.org, data.userId, enterpriseID, OrgCode);

                            CloseAsnLine.EntityKey[] aSNLineKeyLst = new CloseAsnLine.EntityKey[dtos2.Count];

                            for (var i = 0; i < dtos2.Count; i++)
                            {
                                var dto = dtos2[i];
                                aSNLineKeyLst[i] = new CloseAsnLine.EntityKey();
                                aSNLineKeyLst[i].ID = dto.asnlineid;
                                aSNLineKeyLst[i].IDSpecified = true;
                            }

                            CloseAsnLine.MessageBase[] essageBase2 = closeASNLine.Do(context2, aSNLineKeyLst, false, true);
                        }

                        //收货行写入异常原因
                        StringBuilder sb = new StringBuilder();
                        foreach (var dto in dtos)
                        {
                            sb.AppendLine($@"UPDATE rcvline 
SET DescFlexSegments_PrivateDescSeg2 = '{dto.RcvExceptions}'
FROM PM_POLine poline
INNER JOIN PM_ASNLine asnline 
    ON asnline.SrcDocInfo_SrcDocLine_EntityID = poline.ID
INNER JOIN (
    SELECT *, ROW_NUMBER() OVER (
        PARTITION BY SrcDoc_SrcDocLine_EntityID 
        ORDER BY CreatedOn DESC
    ) AS rn 
    FROM PM_RcvLine
) rcvline 
    ON rcvline.SrcDoc_SrcDocLine_EntityID = poline.ID 
    AND rcvline.rn  = 1
WHERE asnline.ID = {dto.asnlineid}");
                        }
                        DbHelperSQL.ExecuteSql(sb.ToString());

                        //回写ASN行
                        //foreach (var dto in dtos)
                        //{
                        //    string sql = $@"update PM_ASNLine set DescFlexField_PrivateDescSeg1 = '{dto.unqualifiyQty}' where  id = " + dto.asnlineid;
                        //    DbHelperSQL.ExecuteSql(sql);


                        //}
                        //PrintDocument print = new PrintDocument();
                        //PrinterSettings.InstalledPrinters
                        //rtn.msg = "收货成功";


                        sendzebra(data, rt, data.userName);
                        rtn.code = 1;
                        return rtn;
                    }


                }
                catch (System.Exception e)
                {
                    rtn.msg = e.Message;
                    rtn.code = 0;
                    return rtn;
                }
            }
            else
            {
                rtn.code = 0;
                rtn.msg = "请选择出货行";
                return rtn;
            }



        }

        public void sendzebra(ASNLineListReciveDTO data, RcvByASN.UFIDACUSTHXBMBMSVRusultDTOData rt, string userName)
        {


            foreach (var item in data.list)
            {

                ASNDTO dto = JsonConvert.DeserializeObject<ASNDTO>(item);


                DataSet rtds = DbHelperSQL.Query(@"select DISTINCT a.Supplier_Code SupCode,s.Name SupName,b.InvLotCode,c.PacksPerUnit,d.name UOM ,a.DocNo from PM_Receivement a 
												left join PM_RcvLine b on b.Receivement = a.id 
												left join CBO_PackageSchema c on c.item = b.ItemInfo_ItemID
												left join Base_UOM_Trl d on d.id = b.StoreUOM
												left join CBO_Supplier_trl s on a.Supplier_Supplier = s.id
												where a.id = " + rt.m_result + " and  b.ItemInfo_ItemID = " + dto.ItemMaster);

                var SupCode = rtds.Tables[0].Rows[0]["SupCode"].ToString();
                var SupName = rtds.Tables[0].Rows[0]["SupName"].ToString();
                var InvLotCode = rtds.Tables[0].Rows[0]["InvLotCode"].ToString();
                var UOM = rtds.Tables[0].Rows[0]["UOM"].ToString();
                var DocNo = rtds.Tables[0].Rows[0]["DocNo"].ToString();
                var PacksPerUnit = rtds.Tables[0].Rows[0]["PacksPerUnit"].ToString();
                if (string.IsNullOrEmpty(PacksPerUnit))
                {
                    string barcode = dto.itemCode + "|" + InvLotCode + "|" + SupCode + "||" + DocNo + "|001";
                    //开始绘制图片
                    int initialWidth = 780, initialHeight = 700;
                    Bitmap theBitmap = new Bitmap(initialWidth, initialHeight);
                    Graphics theGraphics = Graphics.FromImage(theBitmap);
                    Brush bush = new SolidBrush(System.Drawing.Color.Black);//填充的颜色
                                                                            //呈现质量
                    theGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    //背景色
                    theGraphics.Clear(System.Drawing.Color.FromArgb(120, 240, 180));
                    double beishulogo = 1.2;
                    double beishuhege = 0.37;
                    //System.Drawing.Image img = new Bitmap(Application.StartupPath + "\\data\\系统数据\\logo3.png");
                    //theGraphics.DrawImage(img, 55, 0, (float)(img.Width * beishulogo), (float)(img.Height * beishulogo));
                    //System.Drawing.Image img2 = new Bitmap(Application.StartupPath + "\\data\\系统数据\\合格.png");
                    //theGraphics.DrawImage(img2, 500, -25, (float)(img2.Width * beishuhege), (float)(img2.Height * beishuhege));
                    System.Drawing.Font myFont;
                    myFont = new System.Drawing.Font("宋体", 20, FontStyle.Bold);
                    System.Drawing.Font TitleFont;
                    TitleFont = new System.Drawing.Font("宋体", 30, FontStyle.Underline);
                    StringFormat geshi = new StringFormat();
                    geshi.Alignment = StringAlignment.Center; //居中
                                                              //geshi.Alignment = StringAlignment.Far; //右对齐
                    int starty = 100;
                    int jianggey = 40;

                    //Rectangle rect = new Rectangle(0,starty , initialWidth, initialHeight);
                    theGraphics.DrawString("料品标签", TitleFont, bush, 250, 75);
                    theGraphics.DrawString("物料名称：" + dto.itemName, myFont, bush, 25, starty + jianggey * 1);
                    theGraphics.DrawString("物料编码：" + dto.itemCode, myFont, bush, 25, starty + jianggey * 2);
                    theGraphics.DrawString("批 次 号：" + InvLotCode, myFont, bush, 25, starty + jianggey * 3);
                    theGraphics.DrawString("单包数量：", myFont, bush, 25, starty + jianggey * 4);
                    theGraphics.DrawString("单 位：" + UOM, myFont, bush, 285, starty + jianggey * 4);
                    theGraphics.DrawString("数    量：" + dto.qualifiyQty.ToString("0.00"), myFont, bush, 25, starty + jianggey * 5);
                    theGraphics.DrawString("参考库位：", myFont, bush, 25, starty + jianggey * 6);
                    theGraphics.DrawString("供 应 商：" + SupName, myFont, bush, 25, starty + jianggey * 7);
                    Image img3 = getqrcode(barcode);//传入URL返回二维码image
                    theGraphics.DrawImage(img3, 450, 160, (float)(220), (float)(220));
                    //结束图片绘制以上都是绘制图片的代码



                    int totalbytes = 64800;
                    int rowbytes = 90;
                    string hex = ZebraUnity.BitmapToHex(theBitmap, out totalbytes, out rowbytes);//将图片转成ASCii码
                    string mubanstring = "~DGR:ZLOGO.GRF," + totalbytes.ToString() + "," + rowbytes.ToString() + "," + hex;//将图片生成模板指令

                    ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.ZPL;
                    //ZebraPrintHelper.TcpIpAddress = "10.225.82.20";
                    //ZebraPrintHelper.TcpPort = 9100;
                    ZebraPrintHelper.PrinterName = PrinterName;
                    ZebraPrintHelper.PrinterType = DeviceType.DRV;
                    ZebraPrintHelper.PrintCommand(mubanstring);


                    string otherstring = "^XA^FO0,0^XGR:ZLOGO.GRF,1,1^FS";//调用该模板指令
                    otherstring += "^XZ";
                    ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.ZPL;
                    //ZebraPrintHelper.TcpIpAddress = "10.225.82.20";
                    //ZebraPrintHelper.TcpPort = 9100;
                    ZebraPrintHelper.PrinterName = PrinterName;
                    ZebraPrintHelper.PrinterType = DeviceType.DRV;
                    ZebraPrintHelper.PrintCommand(otherstring);

                    ////条码档案
                    //string sql = @"INSERT INTO [dbo].[Cust_BarCodeBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [Code], [Status], [SerialNum], [ID], [SysVersion], [RcvId]) VALUES 
                    //											      ('"+DateTime.Now+ "', '" + DateTime.Now + "', '"+ userName + "', '" + userName + "', '" + barcode + "', 0, 1, " + GuidToLongID().ToString() + ", 0, "+ rt.m_result + ");";
                    //DbHelperSQL.ExecuteSql(sql);
                }
                else
                {
                    var qty = Math.Round(Convert.ToDecimal(PacksPerUnit), 2);
                    var a = Math.Round(Math.Floor(dto.qualifiyQty / qty), 2);
                    var b = Math.Round(Math.Floor(dto.qualifiyQty % qty), 2);

                    for (var i = 0; i < a; i++)
                    {
                        string barcode = dto.itemCode + "|" + InvLotCode + "|" + SupCode + "|" + qty.ToString("0.00") + "|" + DocNo + "|" + (i + 1).ToString("000");

                        //存入条码档案


                        //开始绘制图片
                        int initialWidth = 780, initialHeight = 700;
                        Bitmap theBitmap = new Bitmap(initialWidth, initialHeight);
                        Graphics theGraphics = Graphics.FromImage(theBitmap);
                        Brush bush = new SolidBrush(System.Drawing.Color.Black);//填充的颜色
                                                                                //呈现质量
                        theGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        //背景色
                        theGraphics.Clear(System.Drawing.Color.FromArgb(120, 240, 180));
                        double beishulogo = 1.2;
                        double beishuhege = 0.37;
                        //System.Drawing.Image img = new Bitmap(Application.StartupPath + "\\data\\系统数据\\logo3.png");
                        //theGraphics.DrawImage(img, 55, 0, (float)(img.Width * beishulogo), (float)(img.Height * beishulogo));
                        //System.Drawing.Image img2 = new Bitmap(Application.StartupPath + "\\data\\系统数据\\合格.png");
                        //theGraphics.DrawImage(img2, 500, -25, (float)(img2.Width * beishuhege), (float)(img2.Height * beishuhege));
                        System.Drawing.Font myFont;
                        myFont = new System.Drawing.Font("宋体", 20, FontStyle.Bold);
                        System.Drawing.Font TitleFont;
                        TitleFont = new System.Drawing.Font("宋体", 30, FontStyle.Underline);
                        StringFormat geshi = new StringFormat();
                        geshi.Alignment = StringAlignment.Center; //居中
                                                                  //geshi.Alignment = StringAlignment.Far; //右对齐
                        int starty = 100;
                        int jianggey = 40;

                        //Rectangle rect = new Rectangle(0,starty , initialWidth, initialHeight);
                        theGraphics.DrawString("料品标签", TitleFont, bush, 250, 75);
                        theGraphics.DrawString("物料名称：" + dto.itemName, myFont, bush, 25, starty + jianggey * 1);
                        theGraphics.DrawString("物料编码：" + dto.itemCode, myFont, bush, 25, starty + jianggey * 2);
                        theGraphics.DrawString("批 次 号：" + InvLotCode, myFont, bush, 25, starty + jianggey * 3);
                        theGraphics.DrawString("单包数量：" + qty.ToString("0.00"), myFont, bush, 25, starty + jianggey * 4);
                        theGraphics.DrawString("单 位：" + UOM, myFont, bush, 285, starty + jianggey * 4);
                        theGraphics.DrawString("数    量：" + dto.qualifiyQty.ToString("0.00"), myFont, bush, 25, starty + jianggey * 5);
                        theGraphics.DrawString("参考库位：", myFont, bush, 25, starty + jianggey * 6);
                        theGraphics.DrawString("供 应 商：" + SupName, myFont, bush, 25, starty + jianggey * 7);
                        Image img3 = getqrcode(barcode);//传入URL返回二维码image
                        theGraphics.DrawImage(img3, 450, 160, (float)(220), (float)(220));
                        //结束图片绘制以上都是绘制图片的代码



                        int totalbytes = 64800;
                        int rowbytes = 90;
                        string hex = ZebraUnity.BitmapToHex(theBitmap, out totalbytes, out rowbytes);//将图片转成ASCii码
                        string mubanstring = "~DGR:ZLOGO.GRF," + totalbytes.ToString() + "," + rowbytes.ToString() + "," + hex;//将图片生成模板指令

                        ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.ZPL;
                        //ZebraPrintHelper.TcpIpAddress = "10.225.82.20";
                        //ZebraPrintHelper.TcpPort = 9100;
                        ZebraPrintHelper.PrinterName = PrinterName;
                        ZebraPrintHelper.PrinterType = DeviceType.DRV;
                        ZebraPrintHelper.PrintCommand(mubanstring);


                        string otherstring = "^XA^FO0,0^XGR:ZLOGO.GRF,1,1^FS";//调用该模板指令
                        otherstring += "^XZ";
                        ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.ZPL;
                        //ZebraPrintHelper.TcpIpAddress = "10.225.82.20";
                        //ZebraPrintHelper.TcpPort = 9100;
                        ZebraPrintHelper.PrinterName = PrinterName;
                        ZebraPrintHelper.PrinterType = DeviceType.DRV;
                        ZebraPrintHelper.PrintCommand(otherstring);

                        ////条码档案
                        //string sql = @"INSERT INTO [dbo].[Cust_BarCodeBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [Code], [Status], [SerialNum], [ID], [SysVersion], [RcvId]) VALUES 
                        //										      ('" + DateTime.Now + "', '" + DateTime.Now + "', '" + userName + "', '" + userName + "', '" + barcode + "', 0, "+ (i + 1) + ", " + GuidToLongID().ToString() + ", 0, " + rt.m_result + ");";
                        //DbHelperSQL.ExecuteSql(sql);
                    }

                    if (b > 0)
                    {
                        string barcode = dto.itemCode + "|" + InvLotCode + "|" + SupCode + "|" + b.ToString("0.00") + "|" + DocNo + "|" + (a + 1).ToString("000");
                        //开始绘制图片
                        int initialWidth = 780, initialHeight = 700;
                        Bitmap theBitmap = new Bitmap(initialWidth, initialHeight);
                        Graphics theGraphics = Graphics.FromImage(theBitmap);
                        Brush bush = new SolidBrush(System.Drawing.Color.Black);//填充的颜色
                                                                                //呈现质量
                        theGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        //背景色
                        theGraphics.Clear(System.Drawing.Color.FromArgb(120, 240, 180));
                        double beishulogo = 1.2;
                        double beishuhege = 0.37;
                        //System.Drawing.Image img = new Bitmap(Application.StartupPath + "\\data\\系统数据\\logo3.png");
                        //theGraphics.DrawImage(img, 55, 0, (float)(img.Width * beishulogo), (float)(img.Height * beishulogo));
                        //System.Drawing.Image img2 = new Bitmap(Application.StartupPath + "\\data\\系统数据\\合格.png");
                        //theGraphics.DrawImage(img2, 500, -25, (float)(img2.Width * beishuhege), (float)(img2.Height * beishuhege));
                        System.Drawing.Font myFont;
                        myFont = new System.Drawing.Font("宋体", 20, FontStyle.Bold);
                        System.Drawing.Font TitleFont;
                        TitleFont = new System.Drawing.Font("宋体", 30, FontStyle.Underline);
                        StringFormat geshi = new StringFormat();
                        geshi.Alignment = StringAlignment.Center; //居中
                                                                  //geshi.Alignment = StringAlignment.Far; //右对齐
                        int starty = 100;
                        int jianggey = 40;

                        //Rectangle rect = new Rectangle(0,starty , initialWidth, initialHeight);
                        theGraphics.DrawString("料品标签", TitleFont, bush, 250, 75);
                        theGraphics.DrawString("物料名称：" + dto.itemName, myFont, bush, 25, starty + jianggey * 1);
                        theGraphics.DrawString("物料编码：" + dto.itemCode, myFont, bush, 25, starty + jianggey * 2);
                        theGraphics.DrawString("批 次 号：" + InvLotCode, myFont, bush, 25, starty + jianggey * 3);
                        theGraphics.DrawString("单包数量：" + b.ToString("0.00"), myFont, bush, 25, starty + jianggey * 4);
                        theGraphics.DrawString("单 位：" + UOM, myFont, bush, 285, starty + jianggey * 4);
                        theGraphics.DrawString("数    量：" + dto.qualifiyQty.ToString("0.00"), myFont, bush, 25, starty + jianggey * 5);
                        theGraphics.DrawString("参考库位：", myFont, bush, 25, starty + jianggey * 6);
                        theGraphics.DrawString("供 应 商：" + SupName, myFont, bush, 25, starty + jianggey * 7);

                        Image img3 = getqrcode(barcode);//传入URL返回二维码image
                        theGraphics.DrawImage(img3, 450, 160, (float)(220), (float)(220));
                        //结束图片绘制以上都是绘制图片的代码



                        int totalbytes = 64800;
                        int rowbytes = 90;
                        string hex = ZebraUnity.BitmapToHex(theBitmap, out totalbytes, out rowbytes);//将图片转成ASCii码
                        string mubanstring = "~DGR:ZLOGO.GRF," + totalbytes.ToString() + "," + rowbytes.ToString() + "," + hex;//将图片生成模板指令

                        ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.ZPL;
                        //ZebraPrintHelper.TcpIpAddress = "10.225.82.20";
                        //ZebraPrintHelper.TcpPort = 9100;
                        ZebraPrintHelper.PrinterName = PrinterName;
                        ZebraPrintHelper.PrinterType = DeviceType.DRV;
                        ZebraPrintHelper.PrintCommand(mubanstring);


                        string otherstring = "^XA^FO0,0^XGR:ZLOGO.GRF,1,1^FS";//调用该模板指令
                        otherstring += "^XZ";
                        ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.ZPL;
                        //ZebraPrintHelper.TcpIpAddress = "10.225.82.20";
                        //ZebraPrintHelper.TcpPort = 9100;
                        ZebraPrintHelper.PrinterName = PrinterName;
                        ZebraPrintHelper.PrinterType = DeviceType.DRV;
                        ZebraPrintHelper.PrintCommand(otherstring);

                        ////条码档案
                        //string sql = @"INSERT INTO [dbo].[Cust_BarCodeBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [Code], [Status], [SerialNum], [ID], [SysVersion], [RcvId]) VALUES 
                        //										      ('" + DateTime.Now + "', '" + DateTime.Now + "', '" + userName + "', '" + userName + "', '" + barcode + "', 0, " + (a + 1) + ", " + GuidToLongID().ToString() + ", 0, " + rt.m_result + ");";
                        //DbHelperSQL.ExecuteSql(sql);
                    }
                }




            }






        }

        public Image getqrcode(string content)
        {
            var encoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode qrCode = encoder.Encode(content);
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(12, QuietZoneModules.Two), Brushes.Black, Brushes.White);//如需改变二维码大小，调整12即可
            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap map = new Bitmap(dSize.CodeWidth, dSize.CodeWidth);
            Graphics g = Graphics.FromImage(map);
            render.Draw(g, qrCode.Matrix);
            return map;
        }

        /// <summary>
        /// 创建asn单
        /// </summary>
        /// <returns></returns>
        public Result<List<long>> SetASN(SetASNDto data)
        {
            Result<List<long>> result = new Result<List<long>>();
            try
            {
                DataSet Orgds = DbHelperSQL.Query(@"select id from Base_Organization where Code = '" + data.OrgCode + "'");
                if (Orgds.Tables.Count == 0 || Orgds.Tables[0].Rows.Count == 0)
                {
                    //var er = $@"INSERT INTO [dbo].[Cust_EDIDataTransferLogBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [ErrorMessage], [Message], [Lot], [PackagesCodes], [PackagesNum], [State], [PO], [ASN], [ID], [SysVersion], [Qty], [Type], [ItemMaster]) VALUES 
                    //														  (GETDATE(), GETDATE(), '{data.userCode}', '{data.userCode}', '{"找不到组织" + data.OrgCode}','{JsonConvert.SerializeObject(data)}', '', '', '', 2, 0,0 ,CONVERT(bigint, CONVERT(varbinary, CAST(N'0x' + replace(newid(),'-','') AS char),1)), 0, 0, 1, '');";
                    //var ert = DbHelperSQL.ExecuteSql(er);

                    throw new System.Exception("找不到组织" + data.OrgCode);
                }
                var OrgId = Convert.ToInt64(Orgds.Tables[0].Rows[0]["id"]);

                DataSet Userds = DbHelperSQL.Query(@"select id from Base_User where Code ='" + data.userCode + "'");
                if (Userds.Tables.Count == 0 || Userds.Tables[0].Rows.Count == 0)
                {

                    //var er = $@"INSERT INTO [dbo].[Cust_EDIDataTransferLogBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [ErrorMessage], [Message], [Lot], [PackagesCodes], [PackagesNum], [State], [PO], [ASN], [ID], [SysVersion], [Qty], [Type], [ItemMaster]) VALUES 
                    //														  (GETDATE(), GETDATE(), '{data.userCode}', '{data.userCode}', '{"找不到用户" + data.userCode}','{JsonConvert.SerializeObject(data)}', '', '', '', 2, 0,0 ,CONVERT(bigint, CONVERT(varbinary, CAST(N'0x' + replace(newid(),'-','') AS char),1)), 0, 0, 1, '');";
                    //var ert = DbHelperSQL.ExecuteSql(er);

                    throw new System.Exception("找不到用户" + data.userCode);
                }
                var UserId = Convert.ToInt64(Userds.Tables[0].Rows[0]["id"]);

                SetUpASN.SetUpASNStub stub = new SetUpASN.SetUpASNStub();
                stub.Url = ERPURL + "/U9/Services/UFIDA.U9.PM.PO.ISetUpASN.svc?wsdl";
                var context = CreateContext<SetUpASN.ThreadContext>(OrgId, UserId, enterpriseID, data.OrgCode);


                DataSet Doctypeds = DbHelperSQL.Query(@"select id from PM_ASNDocType where  code = 'ASN01' and org = " + OrgId);
                if (Doctypeds.Tables.Count == 0 || Doctypeds.Tables[0].Rows.Count == 0)
                {
                    //var er = $@"INSERT INTO [dbo].[Cust_EDIDataTransferLogBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [ErrorMessage], [Message], [Lot], [PackagesCodes], [PackagesNum], [State], [PO], [ASN], [ID], [SysVersion], [Qty], [Type], [ItemMaster]) VALUES 
                    //														  (GETDATE(), GETDATE(), '{data.userCode}', '{data.userCode}', '{"在组织" + data.OrgCode + "下找不到对应的ASN单单据类型"}','{JsonConvert.SerializeObject(data)}', '', '', '', 2,0,0 ,CONVERT(bigint, CONVERT(varbinary, CAST(N'0x' + replace(newid(),'-','') AS char),1)), 0, 0, 1, '');";
                    //var ert = DbHelperSQL.ExecuteSql(er);

                    throw new System.Exception("在组织" + data.OrgCode + "下找不到对应的ASN单单据类型");
                }
                var DoctypeId = Convert.ToInt64(Doctypeds.Tables[0].Rows[0]["id"]);

                DataSet Supplierds = DbHelperSQL.Query(@"select id from CBO_Supplier where Code = '" + data.SupplierCode + "' and org = " + OrgId);
                if (Supplierds.Tables.Count == 0 || Supplierds.Tables[0].Rows.Count == 0)
                {
                    //var er = $@"INSERT INTO [dbo].[Cust_EDIDataTransferLogBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [ErrorMessage], [Message], [Lot], [PackagesCodes], [PackagesNum], [State], [PO], [ASN], [ID], [SysVersion], [Qty], [Type], [ItemMaster]) VALUES 
                    //														  (GETDATE(), GETDATE(), '{data.userCode}', '{data.userCode}', '{"在组织" + data.OrgCode + "下找不到供应商" + data.SupplierCode}','{JsonConvert.SerializeObject(data)}', '', '', '', 2, 0,0 ,CONVERT(bigint, CONVERT(varbinary, CAST(N'0x' + replace(newid(),'-','') AS char),1)), 0, 0, 1, '');";
                    //var ert = DbHelperSQL.ExecuteSql(er);

                    throw new System.Exception("在组织" + data.OrgCode + "下找不到供应商" + data.SupplierCode);
                }
                var SupplierId = Convert.ToInt64(Supplierds.Tables[0].Rows[0]["id"]);

                DataSet ansds = DbHelperSQL.Query(@"select count(id) num from PM_ASN where DocNo = '" + data.Ycarrivecode + "' and org = " + OrgId);
                if (ansds.Tables.Count != 0 && ansds.Tables[0].Rows.Count != 0 && Convert.ToInt32(ansds.Tables[0].Rows[0]["num"]) > 0)
                {
                    //var er = $@"INSERT INTO [dbo].[Cust_EDIDataTransferLogBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [ErrorMessage], [Message], [Lot], [PackagesCodes], [PackagesNum], [State], [PO], [ASN], [ID], [SysVersion], [Qty], [Type], [ItemMaster]) VALUES 
                    //														  (GETDATE(), GETDATE(), '{data.userCode}', '{data.userCode}', '{"在组织" + data.OrgCode + "下找不到供应商" + data.SupplierCode}','{JsonConvert.SerializeObject(data)}', '', '', '', 2, 0,0 ,CONVERT(bigint, CONVERT(varbinary, CAST(N'0x' + replace(newid(),'-','') AS char),1)), 0, 0, 1, '');";
                    //var ert = DbHelperSQL.ExecuteSql(er);

                    throw new System.Exception("在组织" + data.OrgCode + "下已有单据编号为" + data.Ycarrivecode + "的ASN单,不能重复创建");
                }

                SetUpASN.UFIDAU9PMPOASNDTOData[] head = new SetUpASN.UFIDAU9PMPOASNDTOData[1];
                head[0] = new SetUpASN.UFIDAU9PMPOASNDTOData();
                head[0].m_createdBy = data.userCode;
                head[0].ASNDocType = DoctypeId;
                head[0].ASNDocType_SKey = new SetUpASN.EntityKey { ID = DoctypeId, IDSpecified = true, EntityType = "UFIDA.U9.PM.ASN.ASNDocType" };
                head[0].ASNDocTypeSpecified = true;
                head[0].Org = OrgId;
                head[0].Org_SKey = new SetUpASN.EntityKey { ID = OrgId, IDSpecified = true, EntityType = "UFIDA.U9.Base.Organization.Organization" };
                head[0].OrgSpecified = true;
                head[0].m_org_Code = data.OrgCode;
                head[0].BillOrg = OrgId;
                head[0].BillOrg_SKey = new SetUpASN.EntityKey { ID = OrgId, IDSpecified = true, EntityType = "UFIDA.U9.Base.Organization.Organization" };
                head[0].BillOrgSpecified = true;
                head[0].m_docNo = data.Ycarrivecode;
                head[0].m_businessDate = data.ShipDate;
                head[0].m_businessDateSpecified = true;
                head[0].m_supplier = new SetUpASN.UFIDAU9CBOSCMSupplierSupplierMISCInfoData
                {
                    Supplier = SupplierId,
                    SupplierSpecified = true,
                    m_code = data.SupplierCode,
                    Id = SupplierId.ToString(),
                    Supplier_SKey = new SetUpASN.EntityKey { ID = SupplierId, IDSpecified = true, EntityType = "	UFIDA.U9.CBO.SCM.Supplier.Supplier" }
                };
                head[0].m_shipDate = data.ShipDate;
                head[0].m_shipDateSpecified = true;
                var list = new SetUpASN.UFIDAU9PMPOASNLineDTOData[data.list.Count];
                var list2 = new ASNCreateLotAndBarCode.UFIDAU9CustBJASNCreateLotAndBarCodeSVASNCreateLotAndBarCodeDTOData[data.list.Count];
                for (var i = 0; i < data.list.Count; i++)
                {
                    var line = data.list[i];

                    DataSet Itemds = DbHelperSQL.Query(@"select id,PurchaseUOM,Name from CBO_ItemMaster where Code = '" + line.ItemCode + "' and org = " + OrgId);
                    if (Itemds.Tables.Count == 0 || Itemds.Tables[0].Rows.Count == 0)
                    {
                        //var er = $@"INSERT INTO [dbo].[Cust_EDIDataTransferLogBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [ErrorMessage], [Message], [Lot], [PackagesCodes], [PackagesNum], [State], [PO], [ASN], [ID], [SysVersion], [Qty], [Type], [ItemMaster]) VALUES 
                        //													  (GETDATE(), GETDATE(), '{data.userCode}', '{data.userCode}', '{"在组织" + data.OrgCode + "下找不到料品" + line.ItemCode}','{JsonConvert.SerializeObject(data)}', '{line.LotCode}', '{line.PackagesCodes}', '{line.PackagesNum}', 2,0,0 ,CONVERT(bigint, CONVERT(varbinary, CAST(N'0x' + replace(newid(),'-','') AS char),1)), 0, {line.ShipQtyTU}, 1, '{line.ItemCode}');";
                        //var ert = DbHelperSQL.ExecuteSql(er);
                        throw new System.Exception("在组织" + data.OrgCode + "下找不到料品" + line.ItemCode);
                    }
                    var ItemId = Convert.ToInt64(Itemds.Tables[0].Rows[0]["id"]);
                    var PurchaseUOM = Convert.ToInt64(Itemds.Tables[0].Rows[0]["PurchaseUOM"]);
                    var ItemName = Convert.ToString(Itemds.Tables[0].Rows[0]["Name"]);

                    list[i] = new SetUpASN.UFIDAU9PMPOASNLineDTOData();
                    list2[i] = new ASNCreateLotAndBarCode.UFIDAU9CustBJASNCreateLotAndBarCodeSVASNCreateLotAndBarCodeDTOData();

                    list[i].m_docLineNo = line.DocLineNo * 10;
                    list[i].m_docLineNoSpecified = true;
                    list[i].CurrentOrg = OrgId;
                    list[i].CurrentOrg_SKey = new SetUpASN.EntityKey { ID = OrgId, IDSpecified = true, EntityType = "UFIDA.U9.Base.Organization.Organization" };
                    list[i].CurrentOrgSpecified = true;
                    list[i].PurOrg = OrgId;
                    list[i].PurOrg_SKey = new SetUpASN.EntityKey { ID = OrgId, IDSpecified = true, EntityType = "UFIDA.U9.Base.Organization.Organization" };
                    list[i].PurOrgSpecified = true;
                    list[i].m_itemInfo = new SetUpASN.UFIDAU9CBOSCMItemItemInfoData
                    {
                        ItemID = ItemId,
                        ItemIDSpecified = true,
                        m_itemCode = line.ItemCode,
                        ItemID_SKey = new SetUpASN.EntityKey { ID = ItemId, IDSpecified = true, EntityType = "UFIDA.U9.CBO.SCM.Item.ItemMaster" },
                        m_itemName = ItemName
                    };

                    list2[i].m_itemID = ItemId;
                    list2[i].m_itemIDSpecified = true;
                    list2[i].m_lotCode = line.LotCode;
                    list2[i].m_qty = line.ShipQtyTU;
                    list2[i].m_qtySpecified = true;
                    list[i].TradeBaseUOM = PurchaseUOM;
                    list[i].TradeBaseUOMSpecified = true;
                    list[i].TradeBaseUOM_SKey = new SetUpASN.EntityKey { ID = PurchaseUOM, IDSpecified = true, EntityType = "UFIDA.U9.Base.UOM.UOM" };
                    list[i].TradeBaseUOM2 = PurchaseUOM;
                    list[i].TradeBaseUOM2Specified = true;
                    list[i].TradeBaseUOM2_SKey = new SetUpASN.EntityKey { ID = PurchaseUOM, IDSpecified = true, EntityType = "UFIDA.U9.Base.UOM.UOM" };
                    list[i].TradeUOM = PurchaseUOM;
                    list[i].TradeUOMSpecified = true;
                    list[i].TradeUOM_SKey = new SetUpASN.EntityKey { ID = PurchaseUOM, IDSpecified = true, EntityType = "UFIDA.U9.Base.UOM.UOM" };
                    list[i].TradeUOM2 = PurchaseUOM;
                    list[i].TradeUOM2Specified = true;
                    list[i].TradeUOM2_SKey = new SetUpASN.EntityKey { ID = PurchaseUOM, IDSpecified = true, EntityType = "UFIDA.U9.Base.UOM.UOM" };
                    list[i].m_planArriveDate = line.PlanArriveDate;
                    list[i].m_planArriveDateSpecified = true;

                    DataSet PODS = DbHelperSQL.Query($@"select a.id poid,b.id polineid,c.id poshiplineid,a.BusinessDate,b.PurQtyTU,b.ReqQtyTU - b.TotalRecievedQtyTU-sum(isnull(d.ShipQtyTU,0)) RcvQty
														from PM_PurchaseOrder a
														left join PM_POLine b on a.id = b.PurchaseOrder
														left join PM_POShipLine c on b.id = c.POLine
														left join PM_ASNLine d on d.SrcDocInfo_SrcDocSubLine_EntityID = c.id and d.status!=3 
														where  a.DocNo = '{line.PurchaseOrder}' and b.DocLineNo = {line.POLineNo}
														GROUP BY  a.id ,b.id ,c.id ,a.BusinessDate,b.PurQtyTU,b.ReqQtyTU ,b.TotalRecievedQtyTU");
                    if (PODS.Tables.Count == 0 || PODS.Tables[0].Rows.Count == 0)
                    {
                        //var er = $@"INSERT INTO [dbo].[Cust_EDIDataTransferLogBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [ErrorMessage], [Message], [Lot], [PackagesCodes], [PackagesNum], [State], [PO], [ASN], [ID], [SysVersion], [Qty], [Type], [ItemMaster]) VALUES 
                        //													  (GETDATE(), GETDATE(), '{data.userCode}', '{data.userCode}', '{"找不到采购订单" + line.PurchaseOrder}','{JsonConvert.SerializeObject(data)}', '{line.LotCode}', '{line.PackagesCodes}', '{line.PackagesNum}', 2, 0,0 ,CONVERT(bigint, CONVERT(varbinary, CAST(N'0x' + replace(newid(),'-','') AS char),1)), 0, {line.ShipQtyTU}, 1, '{line.ItemCode}');";
                        //var ert = DbHelperSQL.ExecuteSql(er);
                        throw new System.Exception("找不到采购订单" + line.PurchaseOrder);
                    }
                    var poid = Convert.ToInt64(PODS.Tables[0].Rows[0]["poid"]);
                    var polineid = Convert.ToInt64(PODS.Tables[0].Rows[0]["polineid"]);
                    var poshiplineid = Convert.ToInt64(PODS.Tables[0].Rows[0]["poshiplineid"]);
                    var BusinessDate = Convert.ToDateTime(PODS.Tables[0].Rows[0]["BusinessDate"]);
                    var PurQtyTU = Convert.ToDecimal(PODS.Tables[0].Rows[0]["PurQtyTU"]);
                    var RcvQty = Convert.ToDecimal(PODS.Tables[0].Rows[0]["RcvQty"]);
                    if (RcvQty < line.ShipQtyTU)
                    {
                        throw new System.Exception("采购订单" + line.PurchaseOrder + "  " + line.DocLineNo + "行的最大可收货数量" + RcvQty + "小于本次收货数量");
                    }
                    list[i].m_srcDocInfo = new SetUpASN.UFIDAU9CBOSCMPropertyTypesSrcDocInfoData
                    {
                        m_srcDoc = new SetUpASN.UFIDAU9BasePropertyTypesBizEntityKeyData { m_entityID = poid, m_entityIDSpecified = true, m_entityType = "UFIDA.U9.PM.PO.PurchaseOrder" },
                        m_srcDocLine = new SetUpASN.UFIDAU9BasePropertyTypesBizEntityKeyData { m_entityID = polineid, m_entityIDSpecified = true, m_entityType = "UFIDA.U9.PM.PO.POLine" },
                        m_srcDocSubLine = new SetUpASN.UFIDAU9BasePropertyTypesBizEntityKeyData { m_entityID = poshiplineid, m_entityIDSpecified = true, m_entityType = "UFIDA.U9.PM.PO.POShipLine" },
                        m_srcDocDate = BusinessDate,
                        m_srcDocDateSpecified = true,
                        m_srcDocNo = line.PurchaseOrder,
                        m_srcDocLineNoSpecified = true,
                        m_srcDocLineNo = line.DocLineNo,
                        m_srcDocSubLineNoSpecified = true
                    };
                    list[i].m_shipQtyTU = line.ShipQtyTU;
                    list[i].m_shipQtyTUSpecified = true;
                    list[i].m_shipQtyTBU = line.ShipQtyTU;
                    list[i].m_shipQtyTBUSpecified = true;
                    list[i].m_pOQtyTU = PurQtyTU;
                    list[i].m_pOQtyTUSpecified = true;
                    list[i].m_pOQtyTBU = PurQtyTU;
                    list[i].m_pOQtyTBUSpecified = true;

                    list[i].m_descFlexField = new SetUpASN.UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData { m_privateDescSeg2 = line.PackagesNum, m_privateDescSeg3 = line.PackagesCodes, m_privateDescSeg4 = line.LotCode };
                }

                head[0].m_aSNLine = list;
                SetUpASN.MessageBase[] outMessages = null;
                var rtn = stub.Do(context, head, new string[] { }, out outMessages);



                List<long> rtnlist = rtn.ToList();

                var qr = $"update PM_ASN set CreatedBy = '{data.userCode}',ModifiedBy = '{data.userCode}' where id = " + rtn[0];
                var rt = DbHelperSQL.ExecuteSql(qr);

                ASNCreateLotAndBarCode.ASNCreateLotAndBarCodeSVStub stub2 = new ASNCreateLotAndBarCode.ASNCreateLotAndBarCodeSVStub();
                stub2.Url = ERPURL + "/U9/Services/UFIDA.U9.Cust.BJ.ASNCreateLotAndBarCodeSV.IASNCreateLotAndBarCodeSV.svc?wsdl";
                var context2 = CreateContext<ASNCreateLotAndBarCode.ThreadContext>(OrgId, UserId, enterpriseID, data.OrgCode);

                ASNCreateLotAndBarCode.MessageBase[] outMessages2 = null;
                stub2.Do(context2, SupplierId, true, rtn[0], true, list2, out outMessages2);


                result.data = rtnlist;
            }
            catch (System.Exception e)
            {
                string errmsg = e.Message.Contains("此错误的创建者未指定") ? (DateTime.Now + "生成ASN单出现问题，请去查看对应日志文件") : e.Message;
                var message = JsonConvert.SerializeObject(data);
                var er = $@"INSERT INTO [dbo].[Cust_EDIDataTransferLogBE] ([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [ErrorMessage], [Message], [Lot], [PackagesCodes], [PackagesNum], [State], [PO], [ASN], [ID], [SysVersion], [Qty], [Type], [ItemMaster]) VALUES 
																			  (GETDATE(), GETDATE(), '{data.userCode}', '{data.userCode}', '{errmsg}','{message.Substring(0, message.Length > 4000 ? 4000 : message.Length)}', '', '', '', 2, 0,0 ,CONVERT(bigint, CONVERT(varbinary, CAST(N'0x' + replace(newid(),'-','') AS char),1)), 0, 0, 1, '');";
                var ert = DbHelperSQL.ExecuteSql(er);

                result.code = -1;
                result.msg = errmsg;
                return result;
            }
            return result;
        }



        [HttpPost]
        public Result<InventoryListLineRTNDTO> getInventoryListLine(InventoryListLineInfoDTO data)
        {
            Result<InventoryListLineRTNDTO> rtn = new Result<InventoryListLineRTNDTO>();
            InventoryListLineRTNDTO InventoryListLineDTO = new InventoryListLineRTNDTO();
            DataSet ds = DbHelperSQL.Query($@"select b.id,b.InventorySheetLine,b.Qty InventoryListLineQty,e.Name WHName,d.Code,d.Name,c.BarCode,c.Qty,c.LineNum from Cust_InventoryListHeadBE a 
										   left join Cust_InventoryListLineBE b on b.InventoryListHeadBE = a.id
										   left join Cust_InventoryListLineDetailBE c on c.InventoryListLineBE = b.id
										   left join CBO_ItemMaster d on d.id = b.ItemMaster 
                                           left join CBO_Wh_Trl e on e.id = a.Wh
										   where a.DocNo = '{data.InventoryListDocNo}' and a.org = {data.org} and b.LineNum = {data.InventoryListLineNo} and d.Code = '{data.ItemMasterCode}'
                                           order by c.LineNum desc");

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                InventoryListLineDTO.InventoryListLineID = Convert.ToInt64(ds.Tables[0].Rows[0]["id"]);
                InventoryListLineDTO.InventorySheetLineID = Convert.ToInt64(ds.Tables[0].Rows[0]["InventorySheetLine"]);
                InventoryListLineDTO.Qty = Convert.ToDecimal(ds.Tables[0].Rows[0]["InventoryListLineQty"]);
                InventoryListLineDTO.ItemMasterCode = Convert.ToString(ds.Tables[0].Rows[0]["Code"]);
                InventoryListLineDTO.ItemMasterName = Convert.ToString(ds.Tables[0].Rows[0]["Name"]);
                InventoryListLineDTO.WHName = Convert.ToString(ds.Tables[0].Rows[0]["WHName"]);
                var detailList = new List<InventoryListLineDetailDto>();

                for (var i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    var row = ds.Tables[0].Rows[i];
                    if (!string.IsNullOrEmpty(row["BarCode"].ToString()))
                    {
                        InventoryListLineDetailDto detail = new InventoryListLineDetailDto();
                        detail.LineNum = Convert.ToInt32(row["LineNum"]);
                        detail.ItemMasterName = Convert.ToString(ds.Tables[0].Rows[0]["Name"]);
                        detail.ItemMasterCode = Convert.ToString(ds.Tables[0].Rows[0]["Code"]);
                        detail.BarCode = Convert.ToString(row["BarCode"]);
                        detail.Qty = Convert.ToDecimal(row["Qty"]);

                        detailList.Add(detail);
                    }
                }
                InventoryListLineDTO.detailList = detailList;

            }
            else
            {
                rtn.code = -1;
                rtn.msg = "未找到该盘点清单行";
                return rtn;
            }
            rtn.data = InventoryListLineDTO;
            rtn.code = 1;
            return rtn;

        }

        /// <summary>
        /// 创建盘点清单明细行
        /// </summary>
        /// <returns></returns>
        public Result<List<long>> CreateInventoryListLineDetail(InventoryListLineDTO data)
        {
            Result<List<long>> result = new Result<List<long>>();
            try
            {
                DataSet Orgds = DbHelperSQL.Query(@"select Code from Base_Organization where id = " + data.OrgID);
                var OrgCode = Convert.ToString(Orgds.Tables[0].Rows[0]["Code"]);

                DataSet Userds = DbHelperSQL.Query(@"select id from Base_User where Code ='" + data.userCode + "'");
                if (Userds.Tables.Count == 0 || Userds.Tables[0].Rows.Count == 0)
                {
                    throw new System.Exception("找不到用户" + data.userCode);
                }
                var UserId = Convert.ToInt64(Userds.Tables[0].Rows[0]["id"]);

                CreateInventoryListLineDetail.CreateInventoryListLineDetailStub stub = new CreateInventoryListLineDetail.CreateInventoryListLineDetailStub();
                stub.Url = ERPURL + "/U9/Services/UFIDA.U9.Cust.HH.InventoryListSV.ICreateInventoryListLineDetail.svc?wsdl";
                var context = CreateContext<CreateInventoryListLineDetail.ThreadContext>(data.OrgID, UserId, enterpriseID, OrgCode);

                string msg = "";
                CreateInventoryListLineDetail.UFIDAU9CustHHCreateInventoryListByInventorySheetInventoryListLineDetailDTOData[] details = new CreateInventoryListLineDetail.UFIDAU9CustHHCreateInventoryListByInventorySheetInventoryListLineDetailDTOData[data.list.Count];
                for (var i = 0; i < data.list.Count(); i++)
                {
                    InventoryListLineDetailDto detail = JsonConvert.DeserializeObject<InventoryListLineDetailDto>(data.list[i]);
                    DataSet barcodeckds = DbHelperSQL.Query($@"select a.LineNum from Cust_InventoryListLineBE a
															left join Cust_InventoryListLineDetailBE b on b.InventoryListLineBE = a.id
															where a.InventorySheetLine = {data.InventorySheetLineID} and b.BarCode = '{detail.BarCode}'");
                    if (barcodeckds.Tables.Count > 0 && barcodeckds.Tables[0].Rows.Count > 0)
                    {
                        msg += $"该盘点单的流水号{barcodeckds.Tables[0].Rows[0]["LineNum"]}的行上已经有条码为{detail.BarCode}的明细行了!;";
                    }

                    details[i] = new CreateInventoryListLineDetail.UFIDAU9CustHHCreateInventoryListByInventorySheetInventoryListLineDetailDTOData();
                    details[i].m_barCode = detail.BarCode;
                    details[i].m_qty = detail.Qty;
                    details[i].m_qtySpecified = true;
                    details[i].m_lineNum = detail.LineNum;
                    details[i].m_lineNumSpecified = true;

                }

                if (msg != "")
                {
                    result.msg = msg;
                    result.code = -1;
                    return result;
                }
                stub.Do(context, data.InventoryListLineID, true, details, data.InventoryListLineQty, true);

                result.msg = "生成成功!";




            }
            catch (System.Exception e)
            {
                string errmsg = e.Message.Contains("此错误的创建者未指定") ? (DateTime.Now + "生成盘点清单明细行出现问题，请去查看对应日志文件") : e.Message;

                result.code = -1;
                result.msg = errmsg;
                return result;
            }

            return result;
        }

        #region 废弃
        /// <summary>
        /// 根据料品查找PO生成ASN单和收货单
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        [HttpPost]
        public Result<string> POToASN(POToASNPara para)
        {
            Result<string> result = new Result<string>();
            //上下文检查
            var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);
            SetUpASN.SetUpASNStub stub = new SetUpASN.SetUpASNStub();
            stub.Url = ERPURL + "/U9/Services/UFIDA.U9.PM.PO.ISetUpASN.svc?wsdl";
            var context = CreateContext<SetUpASN.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode);
            //条码重复检查
            //DataSet barCodeCheckDS =  DbHelperSQL.Query($@"select Code from Cust_BarCodeBE where Code in ({string.Join(",",para.BarCodes.Select(t=> $"'{t}'"))})");
            //if (barCodeCheckDS.Tables[0].Rows.Count > 0)
            //{
            //    List<string> errCodes = new List<string>();
            //    foreach (DataRow row in barCodeCheckDS.Tables[0].Rows)
            //    {
            //        errCodes.Add(row["Code"].ToString());
            //    }
            //    throw new System.Exception($"条码:{string.Join(",",errCodes)} 在系统里已存在");
            //}
            //单据类型
            DataSet Doctypeds = DbHelperSQL.Query(@"select id from PM_ASNDocType where  code = 'ASN01' and org = " + para.OrgID);
            if (Doctypeds.Tables.Count == 0 || Doctypeds.Tables[0].Rows.Count == 0)
            {
                throw new System.Exception("在组织" + ContextCode.OrgCode + "下找不到对应的ASN单单据类型");
            }
            var DoctypeId = Convert.ToInt64(Doctypeds.Tables[0].Rows[0]["id"]);
            //供应商
            DataSet Supplierds = DbHelperSQL.Query(@"select id from CBO_Supplier where Code = '" + para.SupplierCode + "' and org = " + para.OrgID);
            if (Supplierds.Tables.Count == 0 || Supplierds.Tables[0].Rows.Count == 0)
            {
                throw new System.Exception("在组织" + ContextCode.OrgCode + "下找不到供应商" + para.SupplierCode);
            }
            var SupplierId = Convert.ToInt64(Supplierds.Tables[0].Rows[0]["id"]);

            SetUpASN.UFIDAU9PMPOASNDTOData[] head = new SetUpASN.UFIDAU9PMPOASNDTOData[1];
            head[0] = new SetUpASN.UFIDAU9PMPOASNDTOData();
            head[0].m_createdBy = ContextCode.UserName;
            head[0].ASNDocType = DoctypeId;
            head[0].ASNDocType_SKey = new SetUpASN.EntityKey { ID = DoctypeId, IDSpecified = true, EntityType = "UFIDA.U9.PM.ASN.ASNDocType" };
            head[0].ASNDocTypeSpecified = true;
            head[0].Org = para.OrgID;
            head[0].Org_SKey = new SetUpASN.EntityKey { ID = para.OrgID, IDSpecified = true, EntityType = "UFIDA.U9.Base.Organization.Organization" };
            head[0].OrgSpecified = true;
            head[0].m_org_Code = ContextCode.OrgCode;
            head[0].BillOrg = para.OrgID;
            head[0].BillOrg_SKey = new SetUpASN.EntityKey { ID = para.OrgID, IDSpecified = true, EntityType = "UFIDA.U9.Base.Organization.Organization" };
            head[0].BillOrgSpecified = true;
            string asnDocNo = $"PDA{ContextCode.OrgCode}-{DateTime.Now:yyyyMMddHHmm}{new Random().Next(10, 99)}";
            head[0].m_docNo = asnDocNo;
            head[0].m_businessDate = DateTime.Now;
            head[0].m_businessDateSpecified = true;
            head[0].m_supplier = new SetUpASN.UFIDAU9CBOSCMSupplierSupplierMISCInfoData
            {
                Supplier = SupplierId,
                SupplierSpecified = true,
                m_code = para.SupplierCode,
                Id = SupplierId.ToString(),
                Supplier_SKey = new SetUpASN.EntityKey { ID = SupplierId, IDSpecified = true, EntityType = "	UFIDA.U9.CBO.SCM.Supplier.Supplier" }
            };
            head[0].m_shipDate = DateTime.Now;
            head[0].m_shipDateSpecified = true;
            UFIDAU9PMPOASNLineDTOData[] listArray;
            List<UFIDAU9PMPOASNLineDTOData> list = new List<UFIDAU9PMPOASNLineDTOData>();

            //料号列表
            List<string> ItemCodes = new List<string>();
            foreach (var itemAndQty in para.ItemAndQtys)
            {
                ItemCodes.Add(itemAndQty.ItemCode);

            }
            //按料品和供应商找采购订单
            string POShipLineSql = $@"select A.ID as poshiplineid,B.ID as polineid,B.DescFlexSegments_PubDescSeg6 as Version,C.ID as poid,B.PurQtyTU,A.SysVersion,A.ItemInfo_ItemCode,
        A.DeficiencyQtyTU - A.ASNNotToRcvQtyTU as CanToASNQtyTU,
        C.BusinessDate,C.DocNo,B.DocLineNo
        from PM_POShipLine A
        inner join PM_POLine B on A.POLine = B.ID and B.Status = 2
        inner join PM_PurchaseOrder C ON B.PurchaseOrder = C.ID
        where A.ItemInfo_ItemCode in ({string.Join(",", ItemCodes.Select(t => $"'{t}'").ToArray())}) AND C.Supplier_Code = '{para.SupplierCode}' and C.Org = '{para.OrgID}' and A.DeficiencyQtyTU - A.ASNNotToRcvQtyTU != 0
        group by A.DeficiencyQtyTU,A.ASNNotToRcvQtyTU,A.ID,A.SysVersion,A.ItemInfo_ItemCode,B.ID,B.PurQtyTU,B.DocLineNo,B.DescFlexSegments_PubDescSeg6,C.ID,C.BusinessDate,C.DocNo";
            DataSet POShipLineDS = DbHelperSQL.Query(POShipLineSql);
            var rows = POShipLineDS.Tables[0].Rows;
            if (rows.Count == 0)
                throw new System.Exception("未找到任何采购订单");
            //遍历扫描的料品和数量
            foreach (var itemAndQty in para.ItemAndQtys)
            {
                //TODO：待优化
                DataSet Itemds = DbHelperSQL.Query(@"select id,PurchaseUOM,Name from CBO_ItemMaster where Code = '" + itemAndQty.ItemCode + "' and org = " + para.OrgID);
                if (Itemds.Tables.Count == 0 || Itemds.Tables[0].Rows.Count == 0)
                {
                    throw new System.Exception("在组织" + ContextCode.OrgCode + "下找不到料品" + itemAndQty.ItemCode);
                }
                var ItemId = Convert.ToInt64(Itemds.Tables[0].Rows[0]["id"]);
                var PurchaseUOM = Convert.ToInt64(Itemds.Tables[0].Rows[0]["PurchaseUOM"]);
                var ItemName = Convert.ToString(Itemds.Tables[0].Rows[0]["Name"]);
                //2575不限制料品版本
                //string versionSql = "";
                //if (para.OrgID != 1002303140070275)
                //{
                //    versionSql = $" and Version = '{itemAndQty.Version}'";
                //}
                //当前料号对应的采购订单发货行
                var itemRows = POShipLineDS.Tables[0].Select($"ItemInfo_ItemCode = '{itemAndQty.ItemCode}'");
                foreach (var row in itemRows)
                {
                    var listi = new SetUpASN.UFIDAU9PMPOASNLineDTOData();

                    //listi.m_docLineNo = line.DocLineNo * 10;
                    //listi.m_docLineNoSpecified = true;
                    listi.CurrentOrg = para.OrgID;
                    listi.CurrentOrg_SKey = new SetUpASN.EntityKey { ID = para.OrgID, IDSpecified = true, EntityType = "UFIDA.U9.Base.Organization.Organization" };
                    listi.CurrentOrgSpecified = true;
                    listi.PurOrg = para.OrgID;
                    listi.PurOrg_SKey = new SetUpASN.EntityKey { ID = para.OrgID, IDSpecified = true, EntityType = "UFIDA.U9.Base.Organization.Organization" };
                    listi.PurOrgSpecified = true;
                    listi.m_itemInfo = new SetUpASN.UFIDAU9CBOSCMItemItemInfoData
                    {
                        ItemID = ItemId,
                        ItemIDSpecified = true,
                        m_itemCode = itemAndQty.ItemCode,
                        ItemID_SKey = new SetUpASN.EntityKey { ID = ItemId, IDSpecified = true, EntityType = "UFIDA.U9.CBO.SCM.Item.ItemMaster" },
                        m_itemName = ItemName
                    };

                    listi.TradeBaseUOM = PurchaseUOM;
                    listi.TradeBaseUOMSpecified = true;
                    listi.TradeBaseUOM_SKey = new SetUpASN.EntityKey { ID = PurchaseUOM, IDSpecified = true, EntityType = "UFIDA.U9.Base.UOM.UOM" };
                    listi.TradeBaseUOM2 = PurchaseUOM;
                    listi.TradeBaseUOM2Specified = true;
                    listi.TradeBaseUOM2_SKey = new SetUpASN.EntityKey { ID = PurchaseUOM, IDSpecified = true, EntityType = "UFIDA.U9.Base.UOM.UOM" };
                    listi.TradeUOM = PurchaseUOM;
                    listi.TradeUOMSpecified = true;
                    listi.TradeUOM_SKey = new SetUpASN.EntityKey { ID = PurchaseUOM, IDSpecified = true, EntityType = "UFIDA.U9.Base.UOM.UOM" };
                    listi.TradeUOM2 = PurchaseUOM;
                    listi.TradeUOM2Specified = true;
                    listi.TradeUOM2_SKey = new SetUpASN.EntityKey { ID = PurchaseUOM, IDSpecified = true, EntityType = "UFIDA.U9.Base.UOM.UOM" };
                    listi.m_planArriveDate = DateTime.Now; ;
                    listi.m_planArriveDateSpecified = true;

                    var poid = Convert.ToInt64(row["poid"]);
                    var polineid = Convert.ToInt64(row["polineid"]);
                    var poshiplineid = Convert.ToInt64(row["poshiplineid"]);
                    var BusinessDate = Convert.ToDateTime(row["BusinessDate"]);
                    var PurQtyTU = Convert.ToDecimal(row["PurQtyTU"]);
                    var docNo = row["DocNo"].ToString();
                    var docLineNo = Convert.ToInt32(row["DocLineNo"]);
                    listi.m_srcDocInfo = new SetUpASN.UFIDAU9CBOSCMPropertyTypesSrcDocInfoData
                    {
                        m_srcDoc = new SetUpASN.UFIDAU9BasePropertyTypesBizEntityKeyData { m_entityID = poid, m_entityIDSpecified = true, m_entityType = "UFIDA.U9.PM.PO.PurchaseOrder" },
                        m_srcDocLine = new SetUpASN.UFIDAU9BasePropertyTypesBizEntityKeyData { m_entityID = polineid, m_entityIDSpecified = true, m_entityType = "UFIDA.U9.PM.PO.POLine" },
                        m_srcDocSubLine = new SetUpASN.UFIDAU9BasePropertyTypesBizEntityKeyData { m_entityID = poshiplineid, m_entityIDSpecified = true, m_entityType = "UFIDA.U9.PM.PO.POShipLine" },
                        m_srcDocDate = BusinessDate,
                        m_srcDocDateSpecified = true,
                        m_srcDocNo = docNo,
                        m_srcDocLineNoSpecified = true,
                        m_srcDocLineNo = docLineNo,
                        m_srcDocSubLineNoSpecified = true
                    };

                    var canToASNQty = Convert.ToDecimal(row["CanToASNQtyTU"]);
                    //如果数量只够一个发货行或者是最后一个发货行
                    if (itemAndQty.ShipQty <= canToASNQty || row == itemRows.Last())
                    {
                        if (itemAndQty.ShipQty > canToASNQty)
                            throw new System.Exception($"料品 {itemAndQty.ItemCode} 可收货数量大于收货数量");
                        listi.m_shipQtyTU = itemAndQty.ShipQty;
                        listi.m_shipQtyTUSpecified = true;
                        listi.m_shipQtyTBU = itemAndQty.ShipQty;
                        listi.m_shipQtyTBUSpecified = true;
                        listi.m_pOQtyTU = PurQtyTU;
                        listi.m_pOQtyTUSpecified = true;
                        listi.m_pOQtyTBU = PurQtyTU;
                        listi.m_pOQtyTBUSpecified = true;

                        listi.m_descFlexField = new SetUpASN.UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData { m_privateDescSeg1 = itemAndQty.UnQualifiedQty.ToString(), m_privateDescSeg3 = "1", m_privateDescSeg4 = itemAndQty.LotMaster, m_privateDescSeg5 = itemAndQty.ConcessionQty.ToString() };
                        list.Add(listi);
                        break;
                    }
                    else
                    {
                        listi.m_shipQtyTU = canToASNQty;
                        listi.m_shipQtyTUSpecified = true;
                        listi.m_shipQtyTBU = canToASNQty;
                        listi.m_shipQtyTBUSpecified = true;
                        listi.m_pOQtyTU = PurQtyTU;
                        listi.m_pOQtyTUSpecified = true;
                        listi.m_pOQtyTBU = PurQtyTU;
                        listi.m_pOQtyTBUSpecified = true;
                        itemAndQty.ShipQty -= canToASNQty;
                        list.Add(listi);
                    }
                }
            }
            listArray = list.ToArray();
            head[0].m_aSNLine = listArray;
            long[] rtn;
            //审核ASN单

            try
            {
                rtn = stub.Do(context, head, new string[] { }, out SetUpASN.MessageBase[] outMessages);

                ApproveASN.ApproveASNServiceStub approveASNSV = new ApproveASN.ApproveASNServiceStub();
                approveASNSV.Url = ERPURL + "/u9/services/UFIDA.U9.Cust.JGSoft.HongLiPDAProjectSV.PDASV.IApproveASNService.svc?wsdl";
                approveASNSV.Do(CreateContext<ApproveASN.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode), rtn, ContextCode.UserName, out bool DoResult, out bool dors, out ApproveASN.MessageBase[] outMessages1);
            }
            catch (System.Exception ex)
            {
                LogManager.WriteLog($"ASN单审核失败，{ex.Message}", "All");
                result.code = 0;
                result.msg = "收货失败，请稍后再试";
                return result;
            }
            //DbHelperSQL.ExecuteSql($"update PM_ASN set CreatedBy = '{ContextCode.UserName}' where ID = {rtn[0]}");
            ASNLineListReciveDTO asndto = new ASNLineListReciveDTO
            {
                org = para.OrgID,
                userId = para.UserID,
                userName = ContextCode.UserName,
                asnId = rtn[0],
                asnDocNo = asnDocNo
            };
            List<string> lineDtos = new List<string>();
            var closeasnlines = new List<CloseAsnLine.EntityKey>();
            //查生成的ASN单信息
            DataSet asnInfods = DbHelperSQL.Query($@"select B.ID,B.DocLineNo,B.ItemInfo_ItemCode,B.ShipQtyTU,B.DescFlexField_PrivateDescSeg1 as UnQualifiedQty
        ,B.DescFlexField_PrivateDescSeg2 as ConcessionQty,whm.Code as whCode 
        from PM_ASN A with(nolock)
        INNER JOIN PM_ASNLine B ON B.ASN = A.ID
        left join CBO_ItemMaster it on it.id = B.ItemInfo_ItemID
        left join CBO_InventoryInfo iv on iv.ItemMaster = it.id
        left join cbo_wh whm on whm.id = iv.Warehouse 
        WHERE A.ID = {rtn[0]}");
            var asnRows = asnInfods.Tables[0].Rows;
            if (asnRows.Count > 0)
            {
                foreach (DataRow row in asnRows)
                {
                    decimal shipQty = Convert.ToDecimal(string.IsNullOrEmpty(row["ShipQtyTU"].ToString()) ? 0 : row["ShipQtyTU"]);
                    ASNDTO asnLine = new ASNDTO();
                    asnLine.asnlineid = Convert.ToInt64(row["ID"]);
                    asnLine.asnLineno = row["DocLineNo"].ToString();
                    asnLine.itemCode = row["ItemInfo_ItemCode"].ToString();
                    asnLine.unqualifiyQty = Convert.ToDecimal(string.IsNullOrEmpty(row["UnQualifiedQty"].ToString()) ? 0 : row["UnQualifiedQty"]);//Convert.ToDecimal(row["UnQualifiedQty"]),
                    asnLine.qualifiyQty = shipQty - asnLine.unqualifiyQty;
                    asnLine.whcode = row["whCode"].ToString();
                    if (asnLine.qualifiyQty != 0)
                    {
                        lineDtos.Add(JsonConvert.SerializeObject(asnLine));
                    }
                    else
                    {
                        //直接关闭ASN单
                        var closeline = new CloseAsnLine.EntityKey();
                        closeline.ID = Convert.ToInt64(row["ID"]);
                        closeline.IDSpecified = true;
                        closeasnlines.Add(closeline);

                    }
                }
            }
            asndto.list = lineDtos;
            //调用ASN生成收货单
            var rcvresult = postASNLineInfo(asndto);
            //异常处理
            //if (rcvresult.code == 0)
            //{

            //}
            //关闭数量为0的ASN行
            if (closeasnlines.Count > 0)
            {
                CloseAsnLine.CloseASNLineSVStub closeASNLine = new CloseAsnLine.CloseASNLineSVStub();
                closeASNLine.Url = ERPURL + "/U9/Services/UFIDA.U9.PM.PO.ICloseASNLineSV.svc?wsdl";
                CloseAsnLine.ThreadContext context2 = CreateContextCloseASNLine(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode);
                CloseAsnLine.MessageBase[] essageBase2 = closeASNLine.Do(context2, closeasnlines.ToArray(), false, true);
            }
            //获取ASN生成的收货单号，并插入条码档案
            DataSet rcvDS = DbHelperSQL.Query($@"
        select D.DocNo
        from PM_RcvLineExt A
        inner join PM_RcvLine C on A.RcvLine = C.ID
        inner join PM_Receivement D on C.Receivement = D.ID
        where A.SrcASNInfo_SrcDoc_EntityID = {rtn[0]}");
            string rcvDocNo = rcvDS.Tables[0].Rows[0]["DocNo"].ToString();
            StringBuilder batchSql = new StringBuilder();
            batchSql.AppendLine($@"declare	@SNIndex bigint
        if object_id('InnerAllocSerials') is null
            exec	[dbo].[AllocSerials]
        		    @AllocCount = {para.BarCodes.Count},
        		    @StartSN = @SNIndex output
        else
            exec	[dbo].[InnerAllocSerials]
        		    @AllocCount = {para.BarCodes.Count},
        		    @StartSN = @SNIndex output");
            for (int i = 0; i < para.BarCodes.Count; i++)
            {
                string SerialNum = para.BarCodes[i].Split('|')[7].Split('/')[0];
                decimal Qty = Convert.ToDecimal(para.BarCodes[i].Split('|')[4]);
                string barcodeSql = $@"
        insert into Cust_BarCodeBE([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [Code], [Status], [SerialNum], [ID], [SysVersion], [DocNo],[Type],[Org],[Qty])
        values('{DateTime.Now}', '{DateTime.Now}', '{ContextCode.UserCode}', '', '{para.BarCodes[i]}', 0, '{SerialNum}', @SNIndex+{i}, 0, '{rcvDocNo}',1,{para.OrgID},{Qty})";
                batchSql.AppendLine(barcodeSql);
            }
            DbHelperSQL.ExecuteSql(batchSql.ToString());

            result.data = rcvDocNo;
            return result;
        }
        #endregion

        /// <summary>
        /// 根据料品查找PO生成ASN单和收货单(重构)
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        [HttpPost]
        public Result<string> RcvByPO(POToASNPara para)
        {
            Result<string> result = new Result<string>();
            try
            {
                //结账日期特殊控制
                //if (para.BusinessDate >= new DateTime(2024, 3, 26) && para.BusinessDate < new DateTime(2024, 4, 1))
                //{
                //    result.code = 0;
                //    result.msg = $"因账期调整，3月26日至3月31日不能进行收货操作，请调整PDA指定日期";
                //    return result;
                //}
                //上下文检查
                var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);
                bool IsActive = UserActiveCheck(Convert.ToInt64(para.UserID));
                if (!IsActive)
                {
                    result.msg = "当前登录用户不是有效的用户";
                    result.code = 0;
                    return result;
                }
                //EDI供应商检查
                //string qrySql = $@"select DescFlexField_PrivateDescSeg1 from CBO_Supplier where Code = '{para.SupplierCode}' and Org = {para.OrgID}";
                //DataSet suppDS = DbHelperSQL.Query(qrySql);
                //var suppRows = suppDS.Tables[0].Rows;
                //if (suppRows.Count > 0 && Convert.ToBoolean(suppRows[0]["DescFlexField_PrivateDescSeg1"]) == true)
                //{
                //	bool isEDICode = para.BarCodes.All(t => t.Contains("EDI"));
                //	if (!isEDICode)
                //	{
                //		LogManager.WriteLog($"EDI供应商只能使用EDI标签", "All");
                //		result.code = 0;
                //		result.msg = $"EDI供应商只能使用EDI标签";
                //		return result;
                //	}
                //}

                RcvByPO.RcvByPOServiceStub stub = new RcvByPO.RcvByPOServiceStub();
                stub.Url = ERPURL + "/u9/services/UFIDA.U9.Cust.JGSoft.HongLiPDAProjectSV.PDASV.IRcvByPOService.svc";
                var context = CreateContext<RcvByPO.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode);
                RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVRcvByPOServiceDTOData svpara = new RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVRcvByPOServiceDTOData();
                List<RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVASNLineDTOData> asnlines = new List<RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVASNLineDTOData>();

                svpara.m_createBy = ContextCode.UserName;
                svpara.m_org = para.OrgID;
                string asnDocNo = $"PDA{ContextCode.OrgCode}-{para.BusinessDate:yyyyMMddHHmm}{new Random().Next(10, 99)}";
                svpara.m_docNo = asnDocNo;
                svpara.m_businessDate = para.BusinessDate;
                svpara.m_supplierCode = para.SupplierCode;
                svpara.m_shipDate = para.BusinessDate;
                svpara.m_orgSpecified = true;
                svpara.m_businessDateSpecified = true;
                svpara.m_shipDateSpecified = true;

                if (!para.BarCodes[0].Contains("EDI"))
                {


                    //料号列表
                    List<string> ItemCodes = new List<string>();
                    foreach (var itemAndQty in para.ItemAndQtys)
                    {
                        ItemCodes.Add(itemAndQty.ItemCode);

                    }
                    //按料品和供应商找采购订单
                    string POShipLineSql = $@"select A.ID as poshiplineid,B.ID as polineid,B.DescFlexSegments_PubDescSeg6 as Version,C.ID as poid,B.PurQtyTU,A.SysVersion,A.ItemInfo_ItemCode,
A.DeficiencyQtyTU - A.ASNNotToRcvQtyTU as CanToASNQtyTU,
C.BusinessDate,C.DocNo,B.DocLineNo
from PM_POShipLine A
inner join PM_POLine B on A.POLine = B.ID and B.Status = 2
inner join PM_PurchaseOrder C ON B.PurchaseOrder = C.ID
where A.ItemInfo_ItemCode in ({string.Join(",", ItemCodes.Select(t => $"'{t}'").ToArray())}) AND C.Supplier_Code = '{para.SupplierCode}' and C.Org = '{para.OrgID}' and A.DeficiencyQtyTU - A.ASNNotToRcvQtyTU != 0
group by A.DeficiencyQtyTU,A.ASNNotToRcvQtyTU,A.ID,A.SysVersion,A.ItemInfo_ItemCode,B.ID,B.PurQtyTU,B.DocLineNo,B.DescFlexSegments_PubDescSeg6,C.ID,C.BusinessDate,C.DocNo";
                    DataSet POShipLineDS = DbHelperSQL.Query(POShipLineSql);
                    var rows = POShipLineDS.Tables[0].Rows;
                    if (rows.Count == 0)
                    {
                        LogManager.WriteLog($"未找到满足条件的采购订单", "All");
                        result.code = 0;
                        result.msg = $"未找到满足条件的采购订单";
                        return result;
                    }
                    //遍历扫描的料品和数量
                    foreach (var itemAndQty in para.ItemAndQtys)
                    {
                        //当前料号对应的采购订单发货行
                        var itemRows = POShipLineDS.Tables[0].Select($"ItemInfo_ItemCode = '{itemAndQty.ItemCode}'");
                        foreach (var row in itemRows)
                        {
                            RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVASNLineDTOData linedto = new RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVASNLineDTOData();
                            linedto.m_itemCode = itemAndQty.ItemCode;
                            linedto.m_planArriveDate = para.BusinessDate; ;
                            var poid = Convert.ToInt64(row["poid"]);
                            var polineid = Convert.ToInt64(row["polineid"]);
                            var poshiplineid = Convert.ToInt64(row["poshiplineid"]);
                            var BusinessDate = Convert.ToDateTime(row["BusinessDate"]);
                            var PurQtyTU = Convert.ToDecimal(row["PurQtyTU"]);
                            var docNo = row["DocNo"].ToString();
                            var docLineNo = Convert.ToInt32(row["DocLineNo"]);
                            linedto.m_pOID = poid;
                            linedto.m_pOLineID = polineid;
                            linedto.m_pOShipLineID = poshiplineid;
                            linedto.m_pOBusinessDate = BusinessDate;
                            linedto.m_pODocNo = docNo;
                            linedto.m_pODocLineNo = docLineNo;
                            linedto.m_pOIDSpecified = true;
                            linedto.m_pOLineIDSpecified = true;
                            linedto.m_pOShipLineIDSpecified = true;
                            linedto.m_pOBusinessDateSpecified = true;


                            var canToASNQty = Convert.ToDecimal(row["CanToASNQtyTU"]);
                            //如果数量只够一个发货行或者是最后一个发货行
                            if (itemAndQty.ShipQty <= canToASNQty || row == itemRows.Last())
                            {
                                if (itemAndQty.ShipQty > canToASNQty)
                                    throw new System.Exception($"料品 {itemAndQty.ItemCode} 可收货数量大于收货数量");
                                linedto.m_shipQtyTU = itemAndQty.ShipQty;
                                linedto.m_pOPurQtyTU = PurQtyTU;
                                linedto.m_unQualifiedQty = itemAndQty.UnQualifiedQty;
                                linedto.m_lotMaster = itemAndQty.LotMaster;
                                linedto.m_concessionQty = itemAndQty.ConcessionQty;
                                linedto.m_shipQtyTUSpecified = true;
                                linedto.m_pOPurQtyTUSpecified = true;
                                linedto.m_unQualifiedQtySpecified = true;
                                linedto.m_concessionQtySpecified = true;

                                asnlines.Add(linedto);
                                break;
                            }
                            else
                            {
                                linedto.m_shipQtyTU = canToASNQty;
                                linedto.m_pOPurQtyTU = PurQtyTU;
                                itemAndQty.ShipQty -= canToASNQty;
                                linedto.m_shipQtyTUSpecified = true;
                                linedto.m_pOPurQtyTUSpecified = true;

                                asnlines.Add(linedto);
                            }
                        }
                    }
                    svpara.m_aSNLine = asnlines.ToArray();
                }
                else
                {
                    svpara.m_aSNLine = new RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVASNLineDTOData[0];
                }
                svpara.m_barCodes = para.BarCodes.ToArray();

                if (!PublicMethod.BarCodeRepeatCheck(para.BarCodes))
                {
                    LogManager.WriteLog($"网络异常导致的重复提交，条码列表：{string.Join(",", para.BarCodes)}", "All");
                    result.code = 0;
                    result.msg = $"重复提交,请两分钟后再试";
                    return result;
                }
                var stubResult = stub.Do(context, svpara, out RcvByPO.MessageBase[] msg);
                if (stubResult.m_code == 0)
                {
                    LogManager.WriteLog($"收货失败，{stubResult.m_msg}", "All");
                    result.code = 0;
                    result.msg = $"收货失败，{stubResult.m_msg}";
                    return result;
                }
                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"update PM_Receivement set ApprovedBy = '{ContextCode.UserName}' where DocNo = '{stubResult.m_data}' and Org = {para.OrgID}");
                foreach (var item in para.ItemAndQtys)
                {
                    sb.AppendLine($@"update rcvline set DescFlexSegments_PrivateDescSeg2 = '{item.RcvExceptions}'
from PM_Receivement rcv
inner join PM_RcvLine rcvline on rcvline.Receivement = rcv.ID
where rcv.DocNo = '{stubResult.m_data}' and rcv.Org = {para.OrgID} and rcvline.ItemInfo_ItemCode = '{item.ItemCode}'");
                }

                DbHelperSQL.ExecuteSql(sb.ToString());
                result.data = stubResult.m_data;
                return result;
            }
            catch (System.Exception ex)
            {
                LogManager.WriteLog(ex.Message + "\r\n" + ex.StackTrace, "All");
                result.code = 0;
                result.msg = $"发生异常，{ex.Message}";
                return result;
            }
        }

        /// <summary>
        /// 根据料品查找PO生成ASN单和收货单(重构无条码版本)
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        [HttpPost]
        public Result<string> RcvByPONoBarCode(POToASNPara para)
        {
            Result<string> result = new Result<string>();
            try
            {
                //结账日期特殊控制
                if (para.BusinessDate >= new DateTime(2024, 3, 26) && para.BusinessDate < new DateTime(2024, 4, 1))
                {
                    result.code = 0;
                    result.msg = $"因账期调整，3月26日至3月31日不能进行收货操作，请调整PDA指定日期";
                    return result;
                }
                //上下文检查
                var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);
                bool IsActive = UserActiveCheck(Convert.ToInt64(para.UserID));
                if (!IsActive)
                {
                    result.msg = "当前登录用户不是有效的用户";
                    result.code = 0;
                    return result;
                }
                //EDI供应商检查
                //string qrySql = $@"select DescFlexField_PrivateDescSeg1 from CBO_Supplier where Code = '{para.SupplierCode}' and Org = {para.OrgID}";
                //DataSet suppDS = DbHelperSQL.Query(qrySql);
                //var suppRows = suppDS.Tables[0].Rows;
                //if (suppRows.Count > 0 && Convert.ToBoolean(suppRows[0]["DescFlexField_PrivateDescSeg1"]) == true)
                //{
                //	bool isEDICode = para.BarCodes.All(t => t.Contains("EDI"));
                //	if (!isEDICode)
                //	{
                //		LogManager.WriteLog($"EDI供应商只能使用EDI标签", "All");
                //		result.code = 0;
                //		result.msg = $"EDI供应商只能使用EDI标签";
                //		return result;
                //	}
                //}

                RcvByPO.RcvByPOServiceStub stub = new RcvByPO.RcvByPOServiceStub();
                stub.Url = ERPURL + "/u9/services/UFIDA.U9.Cust.JGSoft.HongLiPDAProjectSV.PDASV.IRcvByPOService.svc";
                var context = CreateContext<RcvByPO.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode);
                RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVRcvByPOServiceDTOData svpara = new RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVRcvByPOServiceDTOData();
                List<RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVASNLineDTOData> asnlines = new List<RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVASNLineDTOData>();

                svpara.m_createBy = ContextCode.UserName;
                svpara.m_org = para.OrgID;
                string asnDocNo = $"PDA{ContextCode.OrgCode}-{para.BusinessDate:yyyyMMddHHmm}{new Random().Next(10, 99)}";
                svpara.m_docNo = asnDocNo;
                svpara.m_businessDate = para.BusinessDate;
                svpara.m_supplierCode = para.SupplierCode;
                svpara.m_shipDate = para.BusinessDate;
                svpara.m_orgSpecified = true;
                svpara.m_businessDateSpecified = true;
                svpara.m_shipDateSpecified = true;


                //料号列表
                List<string> ItemCodes = new List<string>();
                foreach (var itemAndQty in para.ItemAndQtys)
                {
                    ItemCodes.Add(itemAndQty.ItemCode);

                }
                //按料品和供应商找采购订单
                string POShipLineSql = $@"select A.ID as poshiplineid,B.ID as polineid,B.DescFlexSegments_PubDescSeg6 as Version,C.ID as poid,B.PurQtyTU,A.SysVersion,A.ItemInfo_ItemCode,
A.DeficiencyQtyTU - A.ASNNotToRcvQtyTU as CanToASNQtyTU,
C.BusinessDate,C.DocNo,B.DocLineNo
from PM_POShipLine A
inner join PM_POLine B on A.POLine = B.ID and B.Status = 2
inner join PM_PurchaseOrder C ON B.PurchaseOrder = C.ID
where A.ItemInfo_ItemCode in ({string.Join(",", ItemCodes.Select(t => $"'{t}'").ToArray())}) AND C.Supplier_Code = '{para.SupplierCode}' and C.Org = '{para.OrgID}' and A.DeficiencyQtyTU - A.ASNNotToRcvQtyTU != 0
group by A.DeficiencyQtyTU,A.ASNNotToRcvQtyTU,A.ID,A.SysVersion,A.ItemInfo_ItemCode,B.ID,B.PurQtyTU,B.DocLineNo,B.DescFlexSegments_PubDescSeg6,C.ID,C.BusinessDate,C.DocNo";
                DataSet POShipLineDS = DbHelperSQL.Query(POShipLineSql);
                var rows = POShipLineDS.Tables[0].Rows;
                if (rows.Count == 0)
                {
                    LogManager.WriteLog($"未找到满足条件的采购订单", "All");
                    result.code = 0;
                    result.msg = $"未找到满足条件的采购订单";
                    return result;
                }
                //遍历扫描的料品和数量
                foreach (var itemAndQty in para.ItemAndQtys)
                {
                    //当前料号对应的采购订单发货行
                    var itemRows = POShipLineDS.Tables[0].Select($"ItemInfo_ItemCode = '{itemAndQty.ItemCode}'");
                    foreach (var row in itemRows)
                    {
                        RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVASNLineDTOData linedto = new RcvByPO.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVASNLineDTOData();
                        linedto.m_itemCode = itemAndQty.ItemCode;
                        linedto.m_planArriveDate = para.BusinessDate; ;
                        var poid = Convert.ToInt64(row["poid"]);
                        var polineid = Convert.ToInt64(row["polineid"]);
                        var poshiplineid = Convert.ToInt64(row["poshiplineid"]);
                        var BusinessDate = Convert.ToDateTime(row["BusinessDate"]);
                        var PurQtyTU = Convert.ToDecimal(row["PurQtyTU"]);
                        var docNo = row["DocNo"].ToString();
                        var docLineNo = Convert.ToInt32(row["DocLineNo"]);
                        linedto.m_pOID = poid;
                        linedto.m_pOLineID = polineid;
                        linedto.m_pOShipLineID = poshiplineid;
                        linedto.m_pOBusinessDate = BusinessDate;
                        linedto.m_pODocNo = docNo;
                        linedto.m_pODocLineNo = docLineNo;
                        linedto.m_pOIDSpecified = true;
                        linedto.m_pOLineIDSpecified = true;
                        linedto.m_pOShipLineIDSpecified = true;
                        linedto.m_pOBusinessDateSpecified = true;


                        var canToASNQty = Convert.ToDecimal(row["CanToASNQtyTU"]);
                        //如果数量只够一个发货行或者是最后一个发货行
                        if (itemAndQty.ShipQty <= canToASNQty || row == itemRows.Last())
                        {
                            if (itemAndQty.ShipQty > canToASNQty)
                                throw new System.Exception($"料品 {itemAndQty.ItemCode} 可收货数量大于收货数量");
                            linedto.m_shipQtyTU = itemAndQty.ShipQty;
                            linedto.m_pOPurQtyTU = PurQtyTU;
                            linedto.m_unQualifiedQty = itemAndQty.UnQualifiedQty;
                            linedto.m_lotMaster = itemAndQty.LotMaster;
                            linedto.m_concessionQty = itemAndQty.ConcessionQty;
                            linedto.m_shipQtyTUSpecified = true;
                            linedto.m_pOPurQtyTUSpecified = true;
                            linedto.m_unQualifiedQtySpecified = true;
                            linedto.m_concessionQtySpecified = true;

                            asnlines.Add(linedto);
                            break;
                        }
                        else
                        {
                            linedto.m_shipQtyTU = canToASNQty;
                            linedto.m_pOPurQtyTU = PurQtyTU;
                            itemAndQty.ShipQty -= canToASNQty;
                            linedto.m_shipQtyTUSpecified = true;
                            linedto.m_pOPurQtyTUSpecified = true;

                            asnlines.Add(linedto);
                        }
                    }
                }
                svpara.m_aSNLine = asnlines.ToArray();
                if (para.BarCodes.Count == 0 && para.ItemAndQtys.Count > 0)
                {
                    foreach (var item in para.ItemAndQtys)
                    {
                        para.BarCodes.Add($"{item.ItemCode}|A01|{DateTime.Now:yyyyMMdd}|{para.SupplierCode}|{item.ShipQty}|{DateTime.Now:HHmmss}|10|1/1|{DateTime.Now:fff}");
                    }
                }
                svpara.m_barCodes = para.BarCodes.ToArray();
                var stubResult = stub.Do(context, svpara, out RcvByPO.MessageBase[] msg);
                if (stubResult.m_code == 0)
                {
                    LogManager.WriteLog($"收货失败，{stubResult.m_msg}", "All");
                    result.code = 0;
                    result.msg = $"收货失败，{stubResult.m_msg}";
                    return result;
                }
                DbHelperSQL.ExecuteSql($"update PM_Receivement set ApprovedBy = '{ContextCode.UserName}' where DocNo = '{stubResult.m_data}' and Org = {para.OrgID}");
                result.data = stubResult.m_data;
                return result;
            }
            catch (System.Exception ex)
            {
                LogManager.WriteLog(ex.Message + "\r\n" + ex.StackTrace, "All");
                result.code = 0;
                result.msg = $"发生异常，{ex.Message}";
                return result;
            }
        }

        /// <summary>
        /// 查询可收货数量
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        [HttpPost]
        public Result<QryCanRcvQtyByItemDto> QryCanRcvQtyByItem(QryCanRcvQtyByItemPara para)
        {
            var result = new Result<QryCanRcvQtyByItemDto>();
            var dto = new QryCanRcvQtyByItemDto();
            //2575不限制料品版本
            //string versionSql = "";
            //if (para.OrgID != 1002303140070275)
            //{
            //    versionSql = $"and B.DescFlexSegments_PubDescSeg6 = '{para.Version}'";
            //}
            //收货数量
            try
            {
                string POShipLineSql = $@"select case when sup.DescFlexField_PrivateDescSeg1 != 'True' then sum(A.DeficiencyQtyTU-A.ASNNotToRcvQtyTU) else sum(A.DeficiencyQtyTU) end as CanToASNQtyTU,
item.Name as ItemName,supp.Name as SupplierName
from PM_POShipLine A
inner join PM_POLine B on A.POLine = B.ID and B.Status = 2
inner join PM_PurchaseOrder C ON B.PurchaseOrder = C.ID
inner join CBO_ItemMaster item on A.ItemInfo_ItemID = item.ID
inner join CBO_Supplier sup on C.Supplier_Supplier = sup.ID
inner join CBO_Supplier_Trl supp on sup.ID= supp.ID and supp.SysMLFlag = 'zh-CN'
where A.ItemInfo_ItemCode in ('{para.ItemCode}') AND C.Supplier_Code = '{para.SupplierCode}' and C.Org = '{para.OrgID}' and B.Status < 3
group by item.Name,supp.Name,item.DescFlexField_PrivateDescSeg10,c.Org,sup.DescFlexField_PrivateDescSeg1";
                DataSet POShipLineDS = DbHelperSQL.Query(POShipLineSql);
                decimal count = 0;
                if (POShipLineDS.Tables[0].Rows.Count > 0 && POShipLineDS.Tables[0].Rows[0]["CanToASNQtyTU"] != DBNull.Value)
                {
                    count = Convert.ToDecimal(POShipLineDS.Tables[0].Rows[0]["CanToASNQtyTU"]);
                    dto.ItemName = POShipLineDS.Tables[0].Rows[0]["ItemName"].ToString();
                    //dto.CarType = POShipLineDS.Tables[0].Rows[0]["CarType"].ToString();
                    dto.SupplierName = POShipLineDS.Tables[0].Rows[0]["SupplierName"].ToString();
                }
                dto.Count = count;
                result.data = dto;
                return result;
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(ex.Message);
            }
        }


        /// <summary>
        /// 生产完工，扫条码生成完工报告
        /// </summary>
        public Result<long> ProductComplete(ProductCompletePara para)
        {

            Result<long> result = new Result<long>();
            StringBuilder insertSql = new StringBuilder();
            //上下文检查
            var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);

            var stub = new CreateCompRpt.CreateCompRptSrvStub();
            stub.Url = ERPURL + "/U9/Services/UFIDA.U9.ISV.MO.ICreateCompRptSrv.svc?wsdl";
            var context = CreateContext<CreateCompRpt.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode);

            var compRtpsList = new List<UFIDAU9ISVMOCompRptDTOData>();
            try
            {
                foreach (var item in para.MOAndQty)
                {
                    string rptDocTypeSql = $@"select top 1 rptdoc.Code
from MO_MO mo
inner join MO_MODocType modoc on mo.MODocType = modoc.ID
inner join MO_CompleteRptDocType rptdoc on modoc.BusinessType = rptdoc.BusinessType 
and modoc.Org = {para.OrgID} and rptdoc.Org = {para.OrgID}
where mo.DocNo = '{item.MO}'";
                    var rptDocTypeDs = DbHelperSQL.Query(rptDocTypeSql);
                    if (rptDocTypeDs.Tables[0].Rows.Count == 0)
                    {
                        result.code = 0;
                        result.msg = "未找到生产订单对应业务类型的完工报告单据类型，请维护";
                        return result;
                    }
                    var compRtp = new UFIDAU9ISVMOCompRptDTOData();
                    // 组织，必填项 
                    compRtp.m_org = new CreateCompRpt.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
                    {
                        m_iD = para.OrgID,
                        m_iDSpecified = true
                    };
                    // 单据类型，必填项
                    compRtp.m_completeDocType = new CreateCompRpt.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
                    {
                        m_code = rptDocTypeDs.Tables[0].Rows[0]["Code"].ToString()
                    };
                    // 生产订单
                    compRtp.m_mO = new CreateCompRpt.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
                    {
                        m_code = item.MO
                    };
                    // 业务日期，必填项
                    compRtp.m_businessDate = para.BusinessDate;
                    compRtp.m_businessDateSpecified = true;
                    compRtp.m_completeDate = para.BusinessDate;
                    compRtp.m_completeDateSpecified = true;
                    // 入库
                    compRtp.m_direction = 0;
                    compRtp.m_directionSpecified = true;
                    compRtp.m_completeQty = item.Qty;
                    compRtp.m_completeQtySpecified = true;
                    compRtp.m_descFlexField = new CreateCompRpt.UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();

                    compRtpsList.Add(compRtp);
                }

                UFIDAU9ISVMOCompRptKeyDTOData[] srvRtn = stub.Do(context, compRtpsList.ToArray(), out CreateCompRpt.MessageBase[] outMessages);
                List<string> RptDocNos = new List<string>();
                foreach (var item in srvRtn)
                {
                    RptDocNos.Add(item.m_docNo);
                }
                insertSql.AppendLine($@"update MO_CompleteRpt Set CreatedBy = '{ContextCode.UserName}' where DocNo in ({string.Join(",", RptDocNos.Select(t => $"'{t}'").ToArray())}) and Org = {para.OrgID}");

                //审核完工报告
                var stub1 = new ApproveCompleteRpt.ApproveCompleteRpt4ExternalSrvStub();
                stub1.Url = ERPURL + "/U9/Services/UFIDA.U9.ISV.MO.IApproveCompleteRpt4ExternalSrv.svc?wsdl";
                var context1 = CreateContext<ApproveCompleteRpt.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode);

                var compRpts = new List<ApproveCompleteRpt.UFIDAU9ISVMOCompRptKeyDTOData>();
                foreach (var item in RptDocNos)
                {
                    var compRpt = new ApproveCompleteRpt.UFIDAU9ISVMOCompRptKeyDTOData();
                    // 完工单号
                    compRpt.m_docNo = item;
                    // 审核标示(审核还是弃审)
                    compRpt.m_operateType = true;
                    compRpt.m_operateTypeSpecified = true;
                    compRpts.Add(compRpt);
                }
                var approveRtn = stub1.Do(context1, compRpts.ToArray(), false, true, out ApproveCompleteRpt.MessageBase[] outMessage1);

                //插入条码使用记录
                string cptSql = $@"select rpt.DocNo as rptDocNo,mo.DocNo as moDocNo
from MO_CompleteRpt rpt
inner join MO_MO mo on rpt.MO = mo.ID
where rpt.DocNo in({string.Join(",", RptDocNos.Select(t => $"'{t}'").ToArray())}) and rpt.Org = {para.OrgID}";
                DataSet cptDt = DbHelperSQL.Query(cptSql);
                int barCodeCount = para.MOAndQty.Sum(t => t.BarCodes.Count);
                insertSql.AppendLine($@"declare	@SNIndex bigint
if object_id('InnerAllocSerials') is null
    exec	[dbo].[AllocSerials]
		    @AllocCount = {barCodeCount},
		    @StartSN = @SNIndex output
else
    exec	[dbo].[InnerAllocSerials]
		    @AllocCount = {barCodeCount},
		    @StartSN = @SNIndex output");
                int idIndex = 0;
                foreach (var mo in para.MOAndQty)
                {
                    var rptDocNo = cptDt.Tables[0].Select($"moDocNo = '{mo.MO}'");
                    foreach (var barcode in mo.BarCodes)
                    {
                        insertSql.AppendLine($@"insert into Cust_BarCodeRecord([ID],[CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy],[Org],[BarCode],[DocType],[DocNo]) 
select @SNIndex+{idIndex},GETDATE(),GETDATE(),'{ContextCode.UserCode}','',{para.OrgID},ID,'完工报告','{rptDocNo[0]["rptDocNo"]}'
from Cust_BarCodeBE where Code = '{barcode}' and Org = {para.OrgID}");
                        idIndex++;
                    }
                }

                DbHelperSQL.ExecuteSql(insertSql.ToString());
                result.data = srvRtn[0].m_iD;
                return result;
            }
            catch (System.Exception ex)
            {
                LogManager.WriteLog($"完工入库：，{ex.Message}\r\n{ex.StackTrace}", "All");
                result.code = 0;
                result.msg = ex.Message;
                return result;
            }
        }
        /// <summary>
        /// 生产完工，扫条码生成完工报告V2
        /// </summary>
        public Result<long> ProductCompleteV2(ProductCompletePara para)
        {
            Result<long> result = new Result<long>();
            try
            {
                //用户活动性检查
                bool IsActive = UserActiveCheck(Convert.ToInt64(para.UserID));
                if (!IsActive)
                {
                    result.msg = "当前登录用户不是有效的用户";
                    result.code = 0;
                    return result;
                }
                StringBuilder insertSql = new StringBuilder();
                //上下文检查
                var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);

                var stub = new ProductComplete.ProductCompleteServiceStub();
                stub.Url = ERPURL + "/u9/services/UFIDA.U9.Cust.JGSoft.HongLiPDAProjectSV.PDASV.IProductCompleteService.svc";
                var context = CreateContext<ProductComplete.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode);
                var svpara = new ProductComplete.UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVProductCompleteDtoData();
                var compRtpsList = new List<ProductComplete.UFIDAU9ISVMOCompRptDTOData>();

                //var compRtpsList = new List<UFIDAU9ISVMOCompRptDTOData>();
                foreach (var item in para.MOAndQty)
                {
                    string rptDocTypeSql = $@"select top 1 rptdoc.Code
from MO_MO mo
inner join MO_MODocType modoc on mo.MODocType = modoc.ID
inner join MO_CompleteRptDocType rptdoc on modoc.BusinessType = rptdoc.BusinessType 
and modoc.Org = {para.OrgID} and rptdoc.Org = {para.OrgID}
where mo.DocNo = '{item.MO}'";
                    var rptDocTypeDs = DbHelperSQL.Query(rptDocTypeSql);
                    if (rptDocTypeDs.Tables[0].Rows.Count == 0)
                    {
                        result.code = 0;
                        result.msg = "未找到生产订单对应业务类型的完工报告单据类型，请维护";
                        return result;
                    }
                    //工单日期和完工日期控制在同一期间
                    string periodCheck = $@"select Count(*) as count from Base_AccountingPeriod p
inner join MO_MO mo on mo.StartDate >= p.FromDate and mo.StartDate < DATEADD(day,1,p.ToDate)
where mo.DocNo = '{item.MO}' and '{para.BusinessDate}' >= p.FromDate and '{para.BusinessDate}' < DATEADD(day,1,p.ToDate)";
                    var periodCheckDs = DbHelperSQL.Query(periodCheck);
                    if (Convert.ToInt32(periodCheckDs.Tables[0].Rows[0]["count"]) == 0)
                    {
                        result.code = 0;
                        result.msg = $"完工时间{para.BusinessDate:yyyyMMdd}与生产订单业务日期不在同一账期，请检查PDA日期设置";
                        return result;
                    }
                    var compRtp = new ProductComplete.UFIDAU9ISVMOCompRptDTOData();
                    // 组织，必填项 
                    compRtp.m_org = new ProductComplete.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
                    {
                        m_iD = para.OrgID,
                        m_iDSpecified = true
                    };
                    // 单据类型，必填项
                    compRtp.m_completeDocType = new ProductComplete.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
                    {
                        m_code = rptDocTypeDs.Tables[0].Rows[0]["Code"].ToString()
                    };
                    // 生产订单
                    compRtp.m_mO = new ProductComplete.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
                    {
                        m_code = item.MO
                    };
                    // 业务日期，必填项
                    compRtp.m_businessDate = para.BusinessDate;
                    compRtp.m_businessDateSpecified = true;
                    compRtp.m_completeDate = para.BusinessDate;
                    compRtp.m_completeDateSpecified = true;
                    // 入库
                    compRtp.m_direction = 0;
                    compRtp.m_directionSpecified = true;
                    compRtp.m_completeQty = item.Qty;
                    compRtp.m_completeQtySpecified = true;
                    compRtp.m_descFlexField = new ProductComplete.UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();

                    compRtpsList.Add(compRtp);
                }

                svpara.m_para = compRtpsList.ToArray();
                svpara.m_createBy = ContextCode.UserCode;
                List<string> allBarcodes = new List<string>();
                foreach (var barcode in para.MOAndQty)
                {
                    allBarcodes.AddRange(barcode.BarCodes);
                }
                svpara.m_barCodes = allBarcodes.ToArray();
                if (!PublicMethod.BarCodeRepeatCheck(allBarcodes))
                {
                    LogManager.WriteLog($"网络异常导致的重复提交，条码列表：{string.Join(",", allBarcodes)}", "All");
                    result.code = 0;
                    result.msg = $"重复提交,请两分钟后再试";
                    return result;
                }
                var srvRtn = stub.Do(context, svpara, out U9BJWebApi.ProductComplete.MessageBase[] msg);
                if (srvRtn.m_code == 0)
                {
                    LogManager.WriteLog($"完工失败，{srvRtn.m_msg}", "All");
                    result.code = 0;
                    result.msg = $"完工失败，{srvRtn.m_msg}";
                    return result;
                }
                return result;
            }
            catch (System.Exception ex)
            {
                LogManager.WriteLog($"{ex.Message}\r\n{ex.StackTrace}", "All");
                result.code = 0;
                result.msg = $"发生异常，{ex.Message}";
                return result;
            }
        }

        /// <summary>
        /// 生成调入单
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public Result<long> CreateTransferIn(CreateTransferInPara para)
        {
            Result<long> result = new Result<long>();
            StringBuilder insertSql = new StringBuilder();
            //条码记录检查
            var exCodes = BarCodeBECheck(para.OrgID, para.BarCodes);
            var exceptCodes = para.BarCodes.Except(exCodes).ToList();
            if (exceptCodes.Count() > 0)
            {
                result.msg = $"条码{string.Join(",", exceptCodes)} 未找到条码记录";
                result.code = 0;
                return result;
            }
            //用户活动性检查
            bool IsActive = UserActiveCheck(Convert.ToInt64(para.UserID));
            if (!IsActive)
            {
                result.msg = "当前登录用户不是有效的用户";
                result.code = 0;
                return result;
            }
            //上下文检查
            var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);

            CommonCreateTransferInSVStub client = new CommonCreateTransferInSVStub();
            client.Url = ERPURL + "/u9/Services/UFIDA.U9.ISV.TransferInISV.ICommonCreateTransferInSV.svc?wsdl";

            UFIDAU9ISVTransferInISVIC_TransferInDTOData[] Boms;
            List<UFIDAU9ISVTransferInISVIC_TransferInDTOData> listBom = new List<UFIDAU9ISVTransferInISVIC_TransferInDTOData>();
            List<UFIDAU9ISVTransferInISVIC_TransInLineDTOData> listBomLine = new List<UFIDAU9ISVTransferInISVIC_TransInLineDTOData>();

            //头
            UFIDAU9ISVTransferInISVIC_TransferInDTOData Bom = new UFIDAU9ISVTransferInISVIC_TransferInDTOData
            {
                m_transInDocType = new CreateTransferIn.UFIDAU9CBOPubControllerCommonArchiveDataDTOData
                {
                    m_iD = para.DocType,//单据类型
                    m_iDSpecified = true
                },
                m_transferType = 0,//调入类型 0为一步式 1为两步式
                m_transferTypeSpecified = true,
                m_org = new CreateTransferIn.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
            };
            Bom.m_org.m_code = ContextCode.OrgCode;
            Bom.m_businessDate = para.BusinessDate;
            Bom.m_businessDateSpecified = true;
            Bom.m_transInLines = new UFIDAU9ISVTransferInISVIC_TransInLineDTOData[] { };
            Bom.sysState = U9BJWebApi.CreateTransferIn.ObjectState.Inserted;
            Bom.m_createdBy = ContextCode.UserName;

            //行
            foreach (var item in para.Items)
            {

                List<UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData> listBomSubline = new List<UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData>();
                UFIDAU9ISVTransferInISVIC_TransInLineDTOData Bom_line = new UFIDAU9ISVTransferInISVIC_TransInLineDTOData
                {
                    m_itemInfo = new CreateTransferIn.UFIDAU9CBOSCMItemItemInfoData
                    {
                        m_itemCode = item.ItemCode//料品                
                    },
                    m_storeUOMQty = item.Qty,//调入数量
                    m_storeUOMQtySpecified = true,
                    m_costUOMQty = item.Qty,  //成本数量
                    m_costUOMQtySpecified = true,
                    m_transInWh = new CreateTransferIn.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
                };
                Bom_line.m_transInWh.m_iD = para.InWhID;//存储地点
                Bom_line.m_transInWh.m_iDSpecified = true;
                Bom_line.sysState = U9BJWebApi.CreateTransferIn.ObjectState.Inserted;
                Bom_line.m_transInSubLines = new UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData[] { };

                //子行
                UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData Bom_subLine = new UFIDAU9ISVTransferInISVIC_TransInSubLineDTOData
                {
                    m_transOutOrg = new CreateTransferIn.UFIDAU9CBOPubControllerCommonArchiveDataDTOData
                    {
                        m_code = ContextCode.OrgCode
                    },
                    m_transOutWh = new CreateTransferIn.UFIDAU9CBOPubControllerCommonArchiveDataDTOData
                    {
                        m_iD = para.OutWhID,
                        m_iDSpecified = true
                    },
                    m_storeUOMQty = item.Qty,
                    m_storeUOMQtySpecified = true,
                    m_costUOMQty = item.Qty,
                    m_costUOMQtySpecified = true
                };
                Bom_subLine.sysState = U9BJWebApi.CreateTransferIn.ObjectState.Inserted;

                listBomSubline.Add(Bom_subLine);//加载子行
                listBomLine.Add(Bom_line);//加载行    
                Bom_line.m_transInSubLines = listBomSubline.ToArray();
            }

            Bom.m_transInLines = listBomLine.ToArray();

            listBom.Add(Bom);
            Boms = listBom.ToArray();

            // 返回参数：消息数组
            CreateTransferIn.UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] returnVal;
            CreateTransferIn.ThreadContext context = CreateContext<CreateTransferIn.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode);// 入口参数：线程上下文              

            // 服务调用
            returnVal = client.Do(context, Boms, out CreateTransferIn.MessageBase[] returnMsg);
            result.data = returnVal[0].m_iD;
            //插入条码使用记录
            insertSql.AppendLine($@"declare	@SNIndex bigint,@BarCodeID bigint
if object_id('InnerAllocSerials') is null
    exec	[dbo].[AllocSerials]
		    @AllocCount = {para.BarCodes.Count},
		    @StartSN = @SNIndex output
else
    exec	[dbo].[InnerAllocSerials]
		    @AllocCount = {para.BarCodes.Count},
		    @StartSN = @SNIndex output");
            for (int i = 0; i < para.BarCodes.Count; i++)
            {
                insertSql.AppendLine($@"select @BarCodeID = COALESCE((select ID from Cust_BarCodeBE where Code = '{para.BarCodes[i]}' and Org = {para.OrgID}),'')

insert into Cust_BarCodeRecord([ID],[CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy],[Org],[BarCode],[DocType],[DocNo]) 
values(@SNIndex+{i},GETDATE(),GETDATE(),'{ContextCode.UserCode}','',{para.OrgID},@BarCodeID,'调入','{returnVal[0].m_code}')");
            }
            DbHelperSQL.ExecuteSql(insertSql.ToString());
            //异常处理
            StringBuilder sb = new StringBuilder();
            bool hasExceiption = false;
            //库存可用量检查
            foreach (var item in para.Items)
            {
                decimal whQty = GetWhQty(item.ItemCode, para.OutWhID, para.OrgID);
                if (whQty < item.Qty)
                {
                    hasExceiption = true;
                    sb.AppendLine($"{item.ItemCode}调出数量大于库存可用量{whQty};");
                }
            }
            if (hasExceiption)
            {
                sb.Insert(0, "已生成开立单据但需手动到ERP处理\r\n");
                result.code = 0;
                result.msg = sb.ToString();
                return result;
            }
            //审核调入单
            var approveStub = new TransInApprove.TransferInBatchApproveSRVStub();
            approveStub.Url = ERPURL + "/u9/services/UFIDA.U9.ISV.TransferInISV.ITransferInBatchApproveSRV.svc?wsdl";
            var queryList = new TransInApprove.UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] { };
            var query = new List<TransInApprove.UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
            var q = new TransInApprove.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            q.m_code = returnVal[0].m_code;//单号
            query.Add(q);
            queryList = query.ToArray();
            string approvedBy = ContextCode.UserName;
            DateTime approvedOn = DateTime.Now;
            var approveMsg = approveStub.Do(CreateContext<TransInApprove.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode), queryList, approvedBy, approvedOn, true);



            return result;
        }

        /// <summary>
        /// 调入单单据类型
        /// </summary>
        /// <param name="OrgID"></param>
        /// <returns></returns>
        [HttpGet]
        public Result<List<IDAndName>> GetTransInDocType(long OrgID)
        {
            DataSet ds = DbHelperSQL.Query($@"select A.ID,B.Name
from InvDoc_TransInDocType A
inner join InvDoc_TransInDocType_Trl B on A.ID = B.ID and A.Org = {OrgID} and B.SysMLFlag = 'zh-CN'");
            var types = new List<IDAndName>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                types.Add(new IDAndName()
                {
                    ID = row["ID"].ToString(),
                    Name = row["Name"].ToString()
                });
            }
            var result = new Result<List<IDAndName>>();
            result.data = types;
            return result;
        }

        /// <summary>
        /// 审核出货单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Result<bool> ApproveShip(ApproveShipPara para)
        {
            var result = new Result<bool>();
            //条码记录检查
            var exCodes = BarCodeBECheck(para.OrgID, para.BarCodes);
            var exceptCodes = para.BarCodes.Except(exCodes).ToList();
            if (exceptCodes.Count() > 0)
            {
                result.msg = $"条码{string.Join(",", exceptCodes)} 未找到条码记录";
                result.code = 0;
                return result;
            }
            result.data = false;
            StringBuilder upSql = new StringBuilder();
            var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);
            //审核前的异常处理
            string whCheckSql = $@"select B.ItemInfo_ItemCode,B.WH,B.ShipQtyTUAmount,
isnull((C.StoreQty - C.ResvStQty - C.ResvOccupyStQty) - 
case when C.[IsProdCancel] = 1 OR C.[MO_EntityID] != 0 or C.[ProductDate] is not null or C.[WP_EntityID] != 0
then C.[StoreQty] else convert(decimal(24,9),0) end,0) as CanUseQty
from SM_Ship A
inner join SM_ShipLine B on B.Ship = A.ID
left join InvTrans_WhQoh C ON B.ItemInfo_ItemID = C.ItemInfo_ItemID AND B.WH = C.Wh
where A.DocNo = '{para.DocNo}'";
            DataSet whCheckDs = DbHelperSQL.Query(whCheckSql.ToString());
            var whCheckRows = whCheckDs.Tables[0].Rows;
            if (whCheckRows.Count > 0)
            {
                List<string> whCheckErrorList = new List<string>();
                //存储地点是否维护检查
                foreach (DataRow whCheckRow in whCheckRows)
                {
                    if (whCheckRow["WH"] == DBNull.Value)
                        whCheckErrorList.Add(whCheckRow["ItemInfo_ItemCode"].ToString());
                }
                if (whCheckErrorList.Count > 0)
                {
                    result.code = 0;
                    result.msg = "料品" + string.Join(",", whCheckErrorList) + "出库存储地点未维护，请联系制单人";
                    return result;
                }
                //库存可用检查
                else
                {
                    foreach (DataRow whCheckRow in whCheckRows)
                    {
                        if (Convert.ToDecimal(whCheckRow["CanUseQty"]) < Convert.ToDecimal(whCheckRow["ShipQtyTUAmount"]))
                        {
                            whCheckErrorList.Add($"料品 {whCheckRow["ItemInfo_ItemCode"]} 库存可用量 {Convert.ToDecimal(whCheckRow["CanUseQty"])} 小于 出货行数量 {Convert.ToDecimal(whCheckRow["ShipQtyTUAmount"])}");
                        }
                    }
                    if (whCheckErrorList.Count > 0)
                    {
                        result.code = 0;
                        result.msg = string.Join(",", whCheckErrorList);
                        return result;
                    }
                }
            }

            foreach (var item in para.ItemAndQtys)
            {
                upSql.AppendLine($@"update SM_ShipLine set DescFlexField_PrivateDescSeg2 = B.DescFlexField_PrivateDescSeg2 + {item.Qty},
ShipConfirmDate = '{para.BusinessDate}'
from SM_Ship A 
inner join SM_ShipLine B ON B.Ship = A.ID
where A.Org = {para.OrgID} and DocNo = '{para.DocNo}' and B.ItemInfo_ItemCode = '{item.ItemCode}'");
            }
            DbHelperSQL.ExecuteSql(upSql.ToString());

            //插入条码使用记录
            StringBuilder insertSql = new StringBuilder();
            insertSql.AppendLine($@"declare	@SNIndex bigint,@BarCodeID bigint
if object_id('InnerAllocSerials') is null
    exec	[dbo].[AllocSerials]
		    @AllocCount = {para.BarCodes.Count},
		    @StartSN = @SNIndex output
else
    exec	[dbo].[InnerAllocSerials]
		    @AllocCount = {para.BarCodes.Count},
		    @StartSN = @SNIndex output");
            for (int i = 0; i < para.BarCodes.Count; i++)
            {
                insertSql.AppendLine($@"select @BarCodeID = COALESCE((select ID from Cust_BarCodeBE where Code = '{para.BarCodes[i]}' and Org = {para.OrgID}),'')

insert into Cust_BarCodeRecord([ID],[CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy],[Org],[BarCode],[DocType],[DocNo]) 
values(@SNIndex+{i},GETDATE(),GETDATE(),'{ContextCode.UserCode}','',{para.OrgID},@BarCodeID,'出货单','{para.DocNo}')");
            }
            DbHelperSQL.ExecuteSql(insertSql.ToString());

            string QtyCheckSql = $@"select sum(Case when B.ShipQtyTUAmount != ISNULL(CAST(NULLIF(B.DescFlexField_PrivateDescSeg2, '')AS decimal), 0) then 1 else 0 end) as UnShipCount,A.Status
from SM_Ship A 
inner join SM_ShipLine B ON B.Ship = A.ID
where A.Org = {para.OrgID} and DocNo = '{para.DocNo}'
group by A.Status";
            DataSet shipDS = DbHelperSQL.Query(QtyCheckSql);
            if (shipDS.Tables[0].Rows.Count > 0 && Convert.ToDecimal(shipDS.Tables[0].Rows[0]["UnShipCount"]) == 0)
            {
                var shipStatu = Convert.ToInt32(shipDS.Tables[0].Rows[0]["Status"]);
                var IsSubmitAndApprove = shipStatu == 1;
                var auditShip = new AuditShip.AuditShipSVStub();
                auditShip.Url = ERPURL + "/u9/services/UFIDA.U9.ISV.SM.IAuditShipSV.svc?wsdl";

                var ShipDocKeyDTOs = new List<AuditShip.UFIDAU9ISVSMDocKeyDTOData>
                {
                    new AuditShip.UFIDAU9ISVSMDocKeyDTOData
                    {
                        m_docNO = para.DocNo
                    }
                };
                //dto.m_docNO = CreateShipSV.ShipSaved[0].m_docNo;
                var returnMsg = auditShip.Do(CreateContext<AuditShip.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode), ShipDocKeyDTOs.ToArray(), false, true, IsSubmitAndApprove, true, false, true, null);
                result.data = true;
            }

            return result;
        }

        /// <summary>
        /// 查询出货单信息
        /// </summary>
        /// <param name="OrgID"></param>
        /// <param name="ShipCode"></param>
        /// <returns></returns>
        [HttpGet]
        public Result<List<ShipLineDto>> QryShip(long OrgID, string ShipCode)
        {
            var result = new Result<List<ShipLineDto>>();
            DataSet ds = DbHelperSQL.Query($@"select B.ItemInfo_ItemCode,B.ItemInfo_ItemName,B.ShipQtyTUAmount,ISNULL(CAST(NULLIF(B.DescFlexField_PrivateDescSeg2, '') AS decimal), 0) as SubmitQty
from SM_Ship A 
inner join SM_ShipLine B ON B.Ship = A.ID
where A.Status in (1,2) and A.Org = {OrgID} and DocNo = '{ShipCode}'
");
            var lines = new List<ShipLineDto>();
            foreach (DataRow item in ds.Tables[0].Rows)
            {
                var line = new ShipLineDto()
                {
                    ItemCode = item["ItemInfo_ItemCode"].ToString(),
                    ItemName = item["ItemInfo_ItemName"].ToString(),
                    Qty = Convert.ToDecimal(item["ShipQtyTUAmount"]),
                    SubmitQty = Convert.ToDecimal(item["SubmitQty"])
                };
                lines.Add(line);
            }
            result.data = lines;
            return result;
        }

        /// <summary>
        /// 查询MO可完工数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Result<QryMOCanCompleteQtyDto> QryMOCanCompleteQty(string MO, long OrgID)
        {
            var result = new Result<QryMOCanCompleteQtyDto>();
            QryMOCanCompleteQtyDto dto = new QryMOCanCompleteQtyDto();
            try
            {
                string QrySql = $@"select mo.DocNo,item.Name,TotalStartQty - TotalCompleteQty as CanCompleteQty,ProductQty,TotalStartQty,
isnull(STUFF((select ','+Code from Cust_BarCodeBE where DocNo = mo.DocNo and Status = 0 FOR XML PATH('')),1,1,''),'') AS NoUseBarCode
from MO_MO mo
inner join CBO_ItemMaster item on mo.ItemMaster = item.ID
where DocNo = '{MO}' and mo.Org = {OrgID}";
                DataSet POShipLineDS = DbHelperSQL.Query(QrySql);
                decimal count = 0, ProductQty = 0, TotalStartQty = 0;
                string NoUseBarCode = "";
                if (POShipLineDS.Tables[0].Rows.Count > 0 && POShipLineDS.Tables[0].Rows[0]["CanCompleteQty"] != DBNull.Value)
                {
                    count = Convert.ToDecimal(POShipLineDS.Tables[0].Rows[0]["CanCompleteQty"]);
                    dto.ItemName = POShipLineDS.Tables[0].Rows[0]["Name"].ToString();
                    //dto.CarType = POShipLineDS.Tables[0].Rows[0]["CarType"].ToString();
                    ProductQty = Convert.ToDecimal(POShipLineDS.Tables[0].Rows[0]["ProductQty"]);
                    TotalStartQty = Convert.ToDecimal(POShipLineDS.Tables[0].Rows[0]["TotalStartQty"]);
                    NoUseBarCode = POShipLineDS.Tables[0].Rows[0]["NoUseBarCode"].ToString();
                }
                dto.Count = count;
                dto.ProductQty = ProductQty;
                dto.TotalStartQty = TotalStartQty;
                dto.NoUseBarCode = NoUseBarCode;
                result.data = dto;
                return result;
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(ex.Message, ex);
            }

        }

        /// <summary>
        /// 查询调入单
        /// </summary>
        /// <param name="OrgID"></param>
        /// <param name="DocNo"></param>
        /// <returns></returns>
        [HttpGet]
        public Result<List<TransInLineDto>> QryTransIn(long OrgID, string DocNo)
        {
            var result = new Result<List<TransInLineDto>>();
            DataSet ds = DbHelperSQL.Query($@"select B.ItemInfo_ItemCode,B.ItemInfo_ItemName,B.StoreUOMQty
from InvDoc_TransferIn A 
inner join InvDoc_TransInLine B on B.TransferIn = A.ID
where A.Status = 0 and A.DocNo = '{DocNo}' and A.Org = {OrgID}
");
            var lines = new List<TransInLineDto>();
            foreach (DataRow item in ds.Tables[0].Rows)
            {
                var line = new TransInLineDto()
                {
                    ItemCode = item["ItemInfo_ItemCode"].ToString(),
                    ItemName = item["ItemInfo_ItemName"].ToString(),
                    Qty = Convert.ToDecimal(item["StoreUOMQty"])
                };
                lines.Add(line);
            }
            result.data = lines;
            return result;
        }

        /// <summary>
        /// 审核调入单
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public Result<bool> ApproveTransIn(ApproveTransInPara para)
        {
            var result = new Result<bool>();
            //条码记录检查
            var exCodes = BarCodeBECheck(para.OrgID, para.BarCodes);
            var exceptCodes = para.BarCodes.Except(exCodes).ToList();
            if (exceptCodes.Count() > 0)
            {
                result.msg = $"条码{string.Join(",", exceptCodes)} 未找到条码记录";
                result.code = 0;
                return result;
            }
            var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);
            var approveStub = new TransInApprove.TransferInBatchApproveSRVStub();
            approveStub.Url = ERPURL + "/u9/services/UFIDA.U9.ISV.TransferInISV.ITransferInBatchApproveSRV.svc?wsdl";
            var queryList = new TransInApprove.UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] { };
            var query = new List<TransInApprove.UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
            var q = new TransInApprove.UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            q.m_code = para.DocNo;//单号
            query.Add(q);
            queryList = query.ToArray();
            string approvedBy = ContextCode.UserName;
            DateTime approvedOn = para.BusinessDate;
            var approveMsg = approveStub.Do(CreateContext<TransInApprove.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode), queryList, approvedBy, approvedOn, true);

            //插入条码使用记录
            StringBuilder insertSql = new StringBuilder();
            insertSql.AppendLine($@"declare	@SNIndex bigint,@BarCodeID bigint
if object_id('InnerAllocSerials') is null
    exec	[dbo].[AllocSerials]
		    @AllocCount = {para.BarCodes.Count},
		    @StartSN = @SNIndex output
else
    exec	[dbo].[InnerAllocSerials]
		    @AllocCount = {para.BarCodes.Count},
		    @StartSN = @SNIndex output");
            for (int i = 0; i < para.BarCodes.Count; i++)
            {
                insertSql.AppendLine($@"select @BarCodeID = COALESCE((select ID from Cust_BarCodeBE where Code = '{para.BarCodes[i]}' and Org = {para.OrgID}),'')

insert into Cust_BarCodeRecord([ID],[CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy],[Org],[BarCode],[DocType],[DocNo]) 
values(@SNIndex+{i},GETDATE(),GETDATE(),'{ContextCode.UserCode}','',{para.OrgID},@BarCodeID,'调入','{para.DocNo}')");
            }
            DbHelperSQL.ExecuteSql(insertSql.ToString());

            result.data = true;
            return result;
        }

        /// <summary>
        /// 收货条码重复检查
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Result<List<BarCodeCheckDto>> BarCodeCheck(BarCodeCheckPara para)
        {
            Result<List<BarCodeCheckDto>> result = new Result<List<BarCodeCheckDto>>();
            List<BarCodeCheckDto> dtos = new List<BarCodeCheckDto>();
            List<string> errCodes = new List<string>();
            result.data = dtos;
            if (para.BarCodes.Count == 0)
                return result;
            //条码重复检查
            //string qrySql = $@"select Code from Cust_BarCodeBE where Org = {para.OrgID} and Code in ({string.Join(",", para.BarCodes.Select(t => $"'{t}'"))})";
            //DataSet barCodeCheckDS = DbHelperSQL.Query(qrySql);
            //if (barCodeCheckDS.Tables[0].Rows.Count > 0)
            //{
            //    foreach (DataRow row in barCodeCheckDS.Tables[0].Rows)
            //    {
            //        errCodes.Add(row["Code"].ToString());
            //    }
            //}
            errCodes = BarCodeBECheck(para.OrgID, para.BarCodes);
            if (errCodes.Count > 0)
            {
                if (errCodes[0].Split('|').Length >= 8)
                {
                    foreach (var codeGroup in errCodes.GroupBy(t => t.Split('|')[0]))
                    {
                        BarCodeCheckDto dto = new BarCodeCheckDto();
                        dto.ItemCode = codeGroup.Key;
                        dto.TotalQty = codeGroup.Sum(t => Convert.ToDecimal(t.Split('|')[4]));
                        foreach (var item in codeGroup)
                        {
                            dto.BarCodes.Add(item);
                            dto.Serials.Add(item.Split('|')[7]);
                        }
                        dtos.Add(dto);
                    }
                }
                //外发标签
                else
                {
                    foreach (var codeGroup in errCodes.GroupBy(t => t.Split('|')[1]))
                    {
                        BarCodeCheckDto dto = new BarCodeCheckDto();
                        dto.ItemCode = codeGroup.Key;
                        dto.TotalQty = codeGroup.Sum(t => Convert.ToDecimal(t.Split('|')[2]));
                        foreach (var item in codeGroup)
                        {
                            dto.BarCodes.Add(item);
                            dto.Serials.Add(item.Split('|')[6]);
                        }
                        dtos.Add(dto);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 条码使用记录检查
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        [HttpPost]
        public Result<List<BarCodeUseCheckDto>> BarCodeUseCheck(BarCodeUseCheckPara para)
        {
            Result<List<BarCodeUseCheckDto>> result = new Result<List<BarCodeUseCheckDto>>();
            List<BarCodeUseCheckDto> dtos = new List<BarCodeUseCheckDto>();
            List<string> errCodes = new List<string>();
            result.data = dtos;
            if (para.BarCodes.Count == 0)
                return result;
            //条码重复检查
            string qrySql = $@"select A.Code
from Cust_BarCodeBE A
left join Cust_BarCodeRecord B on A.ID = B.BarCode
where A.Org = {para.OrgID} and B.DocType = '{para.DocType}'  and A.Code in ({string.Join(",", para.BarCodes.Select(t => $"'{t}'"))})";
            DataSet barCodeCheckDS = DbHelperSQL.Query(qrySql);
            if (barCodeCheckDS.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in barCodeCheckDS.Tables[0].Rows)
                {
                    errCodes.Add(row["Code"].ToString());
                }
            }
            if (para.BarCodes[0].Count(t => t == '|') >= 7)
            {
                foreach (var codeGroup in errCodes.GroupBy(t => t.Split('|')[0]))
                {
                    BarCodeUseCheckDto dto = new BarCodeUseCheckDto();
                    dto.ItemCode = codeGroup.Key;
                    dto.TotalQty = codeGroup.Sum(t => Convert.ToDecimal(t.Split('|')[4]));
                    foreach (var item in codeGroup)
                    {
                        dto.BarCodes.Add(item);
                        dto.Serials.Add(item.Split('|')[7]);
                    }
                    dtos.Add(dto);
                }
            }
            else if (para.BarCodes[0].Count(t => t == '|') == 3)
            {
                foreach (var codeGroup in errCodes.Distinct())
                {
                    BarCodeUseCheckDto dto = new BarCodeUseCheckDto();
                    dto.MO = codeGroup.Split('|')[0];
                    dto.ItemCode = codeGroup.Split('|')[1];
                    dto.TotalQty = Convert.ToDecimal(codeGroup.Split('|')[2]);
                    dto.BarCodes.Add(codeGroup);
                    dto.Serials.Add(codeGroup.Split('|')[3]);
                    dtos.Add(dto);
                }
            }
            return result;
        }

        /// <summary>
        /// 条码失效检查
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        [HttpPost]
        public Result<List<BarCodeUseCheckDto>> BarCodeEffectiveCheck(BarCodeUseCheckPara para)
        {
            Result<List<BarCodeUseCheckDto>> result = new Result<List<BarCodeUseCheckDto>>();
            List<BarCodeUseCheckDto> dtos = new List<BarCodeUseCheckDto>();
            List<string> errCodes = new List<string>();
            result.data = dtos;
            if (para.BarCodes.Count == 0)
                return result;
            //条码重复检查
            string qrySql = $@"select A.Code
from Cust_BarCodeBE A
where A.Org = {para.OrgID} and A.Status = 2 and A.Code in ({string.Join(",", para.BarCodes.Select(t => $"'{t}'"))})";
            DataSet barCodeCheckDS = DbHelperSQL.Query(qrySql);
            if (barCodeCheckDS.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in barCodeCheckDS.Tables[0].Rows)
                {
                    errCodes.Add(row["Code"].ToString());
                }
            }
            if (para.BarCodes[0].Count(t => t == '|') >= 7)
            {
                foreach (var codeGroup in errCodes.GroupBy(t => t.Split('|')[0]))
                {
                    BarCodeUseCheckDto dto = new BarCodeUseCheckDto();
                    dto.ItemCode = codeGroup.Key;
                    dto.TotalQty = codeGroup.Sum(t => Convert.ToDecimal(t.Split('|')[4]));
                    foreach (var item in codeGroup)
                    {
                        dto.BarCodes.Add(item);
                        dto.Serials.Add(item.Split('|')[7]);
                    }
                    dtos.Add(dto);
                }
            }
            else if (para.BarCodes[0].Count(t => t == '|') == 3)
            {
                foreach (var codeGroup in errCodes.Distinct())
                {
                    BarCodeUseCheckDto dto = new BarCodeUseCheckDto();
                    dto.MO = codeGroup.Split('|')[0];
                    dto.ItemCode = codeGroup.Split('|')[1];
                    dto.TotalQty = Convert.ToDecimal(codeGroup.Split('|')[2]);
                    dto.BarCodes.Add(codeGroup);
                    dto.Serials.Add(codeGroup.Split('|')[3]);
                    dtos.Add(dto);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取PDA版本
        /// </summary>
        public Result<GetPDAVersionDto> GetPDAVersion()
        {
            var result = new Result<GetPDAVersionDto>();
            var config = new JsonConfig();
            string LatestVersion = config.GetAppSettings("LatestVersion");
            string DownloadURL = config.GetAppSettings("DownloadURL");
            var dto = new GetPDAVersionDto();
            dto.Version = LatestVersion;
            if (DownloadURL.Contains("{version}"))
            {
                DownloadURL = DownloadURL.Replace("{version}", LatestVersion);
            }
            dto.DownloadURL = DownloadURL;
            result.data = dto;
            return result;
        }

        /// <summary>
        /// 获取PDA菜单相关角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Result<List<string>> GetRoles(ContextPara para)
        {
            var result = new Result<List<string>>();
            string qrySql = $@"select d.Name from Base_UserOrg a
inner join Base_User b on a.[User] = b.ID
inner join Base_UserOrgRole c on c.UserOrg = a.ID
inner join Base_Role_Trl d on c.[Role] = d.ID and d.SysMLFlag = 'zh-CN'
inner join Base_Role d1 on d.ID = d1.ID
inner join Base_Organization e on a.Org = e.ID
where b.ID = {para.UserID} and e.ID = {para.OrgID} and d1.Code like 'PDA%'";
            DataSet RolesDS = DbHelperSQL.Query(qrySql);
            var rows = RolesDS.Tables[0].Rows;
            List<string> roles = new List<string>();
            if (rows.Count > 0)
            {
                foreach (DataRow row in rows)
                {
                    roles.Add(row["Name"].ToString());
                }
            }
            //roles.Add("无EDI收货");
            result.data = roles;
            return result;
        }

        /// <summary>
        /// 装箱扫描生成条码记录
        /// </summary>
        /// <returns></returns>
        public Result<string> PackingBarCodes(PackingBarCodesPara para)
        {
            var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);
            string AllItemCodes = string.Join(",", para.ItemBarCodes);
            string itemBarcodeCheckSql = $@"--将表中的Value列拆分成多个值，用逗号分隔
;WITH CTE1 AS
(
    SELECT DocNo,
    CAST('<X>'+REPLACE(DocNo,',','</X><X>')+'</X>' AS XML) AS XMLValue
    FROM Cust_BarCodeBE
    WHERE CreatedOn > '2024-1-3' and DocNo like '% %'
),
--将给定的字符串Str拆分成多个值，用逗号分隔
CTE2 AS
(
    SELECT Str,
    CAST('<X>'+REPLACE(Str,',','</X><X>')+'</X>' AS XML) AS XMLStr
    FROM (SELECT '{AllItemCodes}' AS Str) T
)
--将拆分后的值进行连接和比较，找出重复的值
SELECT X1.value('.', 'varchar(2000)') AS Duplicate
FROM CTE1 C1
CROSS JOIN CTE2 C2
CROSS APPLY C1.XMLValue.nodes('/X') AS T1(X1)
CROSS APPLY C2.XMLStr.nodes('/X') AS T2(X2)
WHERE X1.value('.', 'varchar(2000)') = X2.value('.', 'varchar(2000)')";
            var itemCheckDS = DbHelperSQL.Query(itemBarcodeCheckSql);
            var itemCheckRows = itemCheckDS.Tables[0].Rows;
            if (itemCheckRows.Count > 0)
            {
                List<string> errItemCodes = new List<string>();
                foreach (DataRow row in itemCheckRows)
                {
                    errItemCodes.Add(row["Duplicate"].ToString());
                }
                return new Result<string>()
                {
                    code = 0,
                    msg = $"条码 {string.Join(",", errItemCodes)} 已被其他箱标签使用"
                };
            }
            StringBuilder batchSql = new StringBuilder();
            batchSql.AppendLine($@"declare	@SNIndex bigint
        if object_id('InnerAllocSerials') is null
            exec	[dbo].[AllocSerials]
        		    @AllocCount = {para.BarCodes.Count},
        		    @StartSN = @SNIndex output
        else
            exec	[dbo].[InnerAllocSerials]
        		    @AllocCount = {para.BarCodes.Count},
        		    @StartSN = @SNIndex output");
            for (int i = 0; i < para.BarCodes.Count; i++)
            {
                string SerialNum = para.BarCodes[i].Split('|')[6].Split('/')[0];
                decimal Qty = Convert.ToDecimal(para.BarCodes[i].Split('|')[2]);
                string itemBarCodes = string.Join(",", para.ItemBarCodes.Where(t => t.Split(' ')[0] == para.BarCodes[i].Split('|')[1]));
                string barcodeSql = $@"
        insert into Cust_BarCodeBE([CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [Code], [Status], [SerialNum], [ID], [SysVersion], [DocNo],[Type],[Org],[Qty])
        values('{DateTime.Now}', '{DateTime.Now}', '{ContextCode.UserCode}', '', '{para.BarCodes[i]}', 0, '{SerialNum}', @SNIndex+{i}, 0, '{itemBarCodes}',1,{para.OrgID},{Qty})";
                batchSql.AppendLine(barcodeSql);
            }
            DbHelperSQL.ExecuteSql(batchSql.ToString());
            return new Result<string>();
        }
        /// <summary>
        /// 库存看板数据获取
        /// </summary>
        /// <param name="orgCode"></param>
        /// <param name="whCode"></param>
        /// <returns></returns>
        [HttpGet]
        public Result<List<WhKanbanDto>> WhKanBanData(string orgCode, string whCode)
        {
            var dataset = DbHelperSQL.Query($"exec Cust_WhKanban1 @orgCode = '{orgCode}',@whCode = '{whCode}',@area = '',@manager = ''");
            var result = new Result<List<WhKanbanDto>>();
            var dtos = new List<WhKanbanDto>();
            var OneYearAgo = DateTime.Now.AddYears(-1).ToString("yyMMdd");
            foreach (DataRow row in dataset.Tables[0].Rows)
            {
                var dto = new WhKanbanDto
                {
                    WhName = row["whName"].ToString(),
                    Area = row["area"].ToString(),
                    ItemInfo_ItemCode = row["ItemInfo_ItemCode"].ToString(),
                    ItemInfo_ItemName = row["ItemInfo_ItemName"].ToString(),
                    ConfirmDate1 = Convert.ToDateTime(row["ConfirmDate1"]).ToString("yyMMdd"),
                    RcvQtyTU1 = Convert.ToDecimal(row["RcvQtyTU1"]),
                    RcvQtyTU2 = Convert.ToDecimal(row["RcvQtyTU2"]),
                    WhQty = Convert.ToDecimal(row["whQty"]),
                    MinQty = Convert.ToDecimal(row["minQty"]),
                    MaxQty = Convert.ToDecimal(row["maxQty"]),
                    Manager = row["manager"].ToString(),
                    ColorFlag = row["colorFlag"].ToString()
                };
                var confirmDate2 = row["ConfirmDate2"] == DBNull.Value ? "" : Convert.ToDateTime(row["ConfirmDate2"]).ToString("yyMMdd");

                dto.ConfirmDate2 = confirmDate2;
                if (dto.WhQty <= dto.RcvQtyTU1)
                {
                    dto.P3Qty = dto.WhQty;
                }
                else if (dto.WhQty > dto.RcvQtyTU1 && dto.WhQty <= dto.RcvQtyTU1 + dto.RcvQtyTU2)
                {
                    dto.P3Qty = dto.RcvQtyTU1;
                    dto.P2Qty = dto.WhQty - dto.RcvQtyTU1;
                }
                else if (dto.WhQty > dto.RcvQtyTU1 + dto.RcvQtyTU2)
                {
                    dto.P3Qty = dto.RcvQtyTU1;
                    dto.P2Qty = dto.RcvQtyTU2;
                    dto.P1Qty = dto.WhQty - (dto.RcvQtyTU1 + dto.RcvQtyTU2);
                    dto.ConfirmDate3 = OneYearAgo;
                }
                if (dto.P2Qty == 0)
                    dto.ConfirmDate2 = "";
                dtos.Add(dto);
            }
            result.data = dtos;
            return result;
        }
        /// <summary>
        /// 送货看板数据获取
        /// </summary>
        /// <param name="orgCode"></param>
        /// <returns></returns>
        [HttpGet]
        public Result<List<ASNKanbanDto>> ASNKanBanData(string orgCode)
        {
            var dataset = DbHelperSQL.Query($"exec Cust_ASNKanban @orgCode = '{orgCode}'");
            var result = new Result<List<ASNKanbanDto>>();
            var dtos = new List<ASNKanbanDto>();
            foreach (DataRow row in dataset.Tables[0].Rows)
            {
                var dto = new ASNKanbanDto
                {
                    unPort = row["unPort"].ToString(),
                    DeliveryDate = Convert.ToDateTime(row["DeliveryDate"]).ToString("yyyy-MM-dd"),
                    DeliveryTime = row["DeliveryTime"].ToString(),
                    suppName = row["suppName"].ToString(),
                    DocNo = row["DocNo"].ToString(),
                    ItemInfo_ItemCode = row["ItemInfo_ItemCode"].ToString(),
                    ItemInfo_ItemName = row["ItemInfo_ItemName"].ToString(),
                    POQtyTU = Convert.ToDecimal(row["POQtyTU"]),
                    ShipQtyTU = Convert.ToDecimal(row["ShipQtyTU"]),
                    TotalRcvQtyTU = Convert.ToDecimal(row["TotalRcvQtyTU"]),
                    whName = row["whName"].ToString(),
                    rcvException = row["rcvException"].ToString(),
                };
                dtos.Add(dto);
            }
            result.data = dtos;
            return result;
        }
        /// <summary>
        /// U9登录接口，不使用服务
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        [HttpGet]
        public Result<IDAndName> U9Login(string UserName, string Password)
        {
            //参数检查
            var result = new Result<IDAndName>();
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password))
            {
                result.code = 0;
                result.msg = "用户名或密码不能为空";
                return result;
            }
            //账号密码验证
            string PW = DESEncrypt.U9Encrypt(Password);
            string pwsql = $"select Name from Base_User WHERE code='{UserName}' and password=upper(substring(sys.fn_VarBinToHexStr(hashbytes('MD5', CAST('{PW}' as varchar(50)) + convert(char(36),base_user.salt))),3,32))";
            var DocNoTable = DbHelperSQL.Query(pwsql);
            if (DocNoTable.Tables[0].Rows.Count == 0)
            {
                result.code = 0;
                result.msg = "用户名或密码错误";
                return result;
            }
            else
            {
                result.data = new IDAndName
                {
                    ID = AESCrypto.Encrypt(UserName),
                    Name = DocNoTable.Tables[0].Rows[0]["Name"].ToString()
                };
                return result;
            }
        }

        /// <summary>
        /// 根据用户获取组织
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        [HttpGet]
        public Result<List<Organization>> UserOrganizationList(string username)
        {
            if (string.IsNullOrEmpty(username))
            {
                return new Result<List<Organization>>();
            }
            DataSet ds = DbHelperSQL.Query($@"select org.ID,org.Code,orgt.Name
from Base_UserOrg uo
inner join Base_User u on uo.[User] = u.ID
inner join Base_Organization org on uo.Org = org.ID
inner join Base_Organization_Trl orgt on uo.Org = orgt.ID
where u.Code = '{username}' and org.isoperatingorg=1");
            List<Organization> DTOs = new List<Organization>();
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Organization dto = new Organization();
                        dto.ID = Convert.ToInt64(dt.Rows[i]["ID"]);
                        dto.Name = dt.Rows[i]["Code"].ToString() + "-" + dt.Rows[i]["Name"].ToString();
                        dto.Code = dt.Rows[i]["Code"].ToString();

                        DTOs.Add(dto);
                    }

                }
            }
            Result<List<Organization>> rtn = new Result<List<Organization>>();
            rtn.data = DTOs;
            return rtn;
        }

        /// <summary>
        /// 查询MO可完工数量（成品入库）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Result<QryMOCanCompleteQtyDto> QryMOCanCompleteQty1(string MO, long OrgID)
        {
            var result = new Result<QryMOCanCompleteQtyDto>();
            QryMOCanCompleteQtyDto dto = new QryMOCanCompleteQtyDto();
            try
            {
                string QrySql = $@"select mo.DocNo,item.Name,TotalStartQty - TotalCompleteQty as CanCompleteQty,ProductQty,TotalStartQty
from MO_MO mo
inner join CBO_ItemMaster item on mo.ItemMaster = item.ID
where DocNo = '{MO}' and mo.Org = {OrgID}";
                DataSet POShipLineDS = DbHelperSQL.Query(QrySql);
                decimal count = 0, ProductQty = 0, TotalStartQty = 0;
                if (POShipLineDS.Tables[0].Rows.Count > 0 && POShipLineDS.Tables[0].Rows[0]["CanCompleteQty"] != DBNull.Value)
                {
                    count = Convert.ToDecimal(POShipLineDS.Tables[0].Rows[0]["CanCompleteQty"]);
                    dto.ItemName = POShipLineDS.Tables[0].Rows[0]["Name"].ToString();
                    //dto.CarType = POShipLineDS.Tables[0].Rows[0]["CarType"].ToString();
                    ProductQty = Convert.ToDecimal(POShipLineDS.Tables[0].Rows[0]["ProductQty"]);
                    TotalStartQty = Convert.ToDecimal(POShipLineDS.Tables[0].Rows[0]["TotalStartQty"]);
                }
                dto.Count = count;
                dto.ProductQty = ProductQty;
                dto.TotalStartQty = TotalStartQty;
                result.data = dto;
                return result;
            }
            catch (System.Exception ex)
            {
                throw new System.Exception(ex.Message, ex);
            }

        }
        /// <summary>
        /// PDA创建成品入库单
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public Result<string> PDARcvRptDoc(ProductCompletePara para)
        {
            //上下文检查
            var ContextCode = PublicMethod.CheckContext(para.OrgID, para.UserID);
            var stub = new CreateRcvRptDoc.PDARcvRptDocServiceStub();
            stub.Url = ERPURL + "/u9/services/UFIDA.U9.Cust.JGSoft.HongLiPDAProjectSV.PDASV.IPDARcvRptDocService.svc";
            var context = CreateContext<CreateRcvRptDoc.ThreadContext>(para.OrgID, para.UserID, enterpriseID, ContextCode.OrgCode);
            var svparas = new List<CreateRcvRptDoc.UFIDAU9ISVMOCompleteDocInfoDTOData>();
            var svpara = new UFIDAU9ISVMOCompleteDocInfoDTOData();

            var result = new Result<string>();
            //单据类型检查
            string rptDocTypeSql = $@"select top 1 rptdoc.Code
from MO_MO mo
inner join MO_MODocType modoc on mo.MODocType = modoc.ID
inner join Complete_RcvRptDocType rptdoc on modoc.BusinessType = rptdoc.BusinessType 
and modoc.Org = {para.OrgID} and rptdoc.Org = {para.OrgID}
where mo.DocNo = '{para.MOAndQty[0].MO}'";
            var rptDocTypeDs = DbHelperSQL.Query(rptDocTypeSql);
            if (rptDocTypeDs.Tables[0].Rows.Count == 0)
            {
                result.code = 0;
                result.msg = "未找到生产订单对应业务类型的入库单单据类型，请维护";
                return result;
            }
            //查出生产订单和条码使用档案信息
            string moInfoSql = $@"select mo.ID,mo.DocNo,item.code itemCode,wh.Code whCode
from MO_MO mo
inner join CBO_ItemMaster item on mo.ItemMaster = item.ID
inner join CBO_Wh wh on mo.CompleteWh = wh.ID
where mo.DocNo in ({PublicMethod.StringJoin(para.MOAndQty.Select(t => t.MO))})";
            var moInfoDS = DbHelperSQL.Query(moInfoSql);

            var allBarCodes = new List<string>();
            foreach (var mo in para.MOAndQty)
            {
                allBarCodes.AddRange(mo.BarCodes);
            }
            string bcInfoSql = $@"select BarCode,CurQty from BC_BarCodeUsed 
where CopyOfBarCodeApp = 0 and BarCode in({PublicMethod.StringJoin(allBarCodes)})";
            var bcInfoDS = DbHelperSQL.Query(bcInfoSql);
            var bcInfoDic = new Dictionary<string, decimal>();
            foreach (DataRow row in bcInfoDS.Tables[0].Rows)
            {
                bcInfoDic.Add(row[0].ToString(), Convert.ToDecimal(row[1]));
            }

            svpara.m_docType = new CreateRcvRptDoc.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
            {
                m_code = rptDocTypeDs.Tables[0].Rows[0]["Code"].ToString()
            };
            var rcvRptList = new List<UFIDAU9ISVMOWOInfoDTOData>();
            foreach (var mo in para.MOAndQty)
            {
                var moRow = moInfoDS.Tables[0].Select($"DocNo = '{mo.MO}'")[0];
                var rcvRpt = new UFIDAU9ISVMOWOInfoDTOData();
                rcvRpt.m_mOKey = new UFIDAU9ISVMOWOKeyData()
                {
                    m_docNo = mo.MO,
                    m_iD = Convert.ToInt64(moRow["ID"]),
                    m_iDSpecified = true,
                    m_orgID = para.OrgID
                };
                rcvRpt.m_item = new CreateRcvRptDoc.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
                {
                    m_code = moRow["itemCode"].ToString()
                };
                rcvRpt.m_wh = new CreateRcvRptDoc.UFIDAU9CBOPubControllerCommonArchiveDataDTOData()
                {
                    m_code = moRow["whCode"].ToString()
                };
                rcvRpt.m_completeQty = mo.Qty;
                rcvRpt.m_completeQtySpecified = true;

                rcvRpt.m_rcvLotEffectivedate = new DateTime(1900, 1, 1);
                rcvRpt.m_rcvLotEffectivedateSpecified = true;

                rcvRptList.Add(rcvRpt);
                svpara.m_completeList = rcvRptList.ToArray();
                svparas.Add(svpara);
            }

            var pdapara = new UFIDAU9CustJGSoftHongLiPDAProjectSVPDASVPDARcvRptDocDtoData();
            pdapara.m_rcvRpts = svparas.ToArray();
            pdapara.m_barCodes = allBarCodes.ToArray();
            var svResult = stub.Do(context, pdapara, out _);
            result = new Result<string>()
            {
                code = svResult.m_code,
                data = svResult.m_data,
                msg = string.IsNullOrEmpty(svResult.m_msg) ? "" : System.Text.RegularExpressions.Regex.Replace(svResult.m_msg, "<a[^>]*>(.*?)</a>", string.Empty)
            };
            return result;
        }
        /// <summary>
        /// 获取生产订单所有条码的数量
        /// </summary>
        /// <param name="MODocNo"></param>
        /// <returns></returns>
        [HttpGet]
        public Result<List<BarCodeQtyDto>> BarCodeQty(string MODocNo)
        {
            string bcInfoSql = $@"select BarCode,CurQty from BC_BarCodeUsed 
where CopyOfBarCodeApp = 0 and DocNo = '{MODocNo}'";
            var bcInfoDS = DbHelperSQL.Query(bcInfoSql);
            var dtos = new List<BarCodeQtyDto>();
            foreach (DataRow row in bcInfoDS.Tables[0].Rows)
            {
                var dto = new BarCodeQtyDto
                {
                    MO = MODocNo,
                    BarCode = row[0].ToString(),
                    Qty = Convert.ToDecimal(row[1])
                };
                dtos.Add(dto);
            }
            return new Result<List<BarCodeQtyDto>>()
            {
                data = dtos,
            };
        }


        /// <summary>
        /// 用户活动性检查
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        private bool UserActiveCheck(long UserID)
        {
            string qrySql = $@"select IsAlive from Base_User where ID = {UserID}";
            DataSet activeDS = DbHelperSQL.Query(qrySql);
            var rows = activeDS.Tables[0].Rows;
            if (rows.Count > 0 && Convert.ToBoolean(rows[0]["IsAlive"]))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 获取库存可用量
        /// </summary>
        /// <returns></returns>
        private decimal GetWhQty(string ItemCode, long WhID, long OrgID)
        {
            string sql = $@"select A.ItemInfo_ItemID as ItemInfo_ItemID,
isnull( case  when A2.[ItemFormAttribute] in (16, 22) then A.[ItemInfo_ItemName] else A2.[Name] end ,'') as [ItemSeg_Name], 
sum((((A.[StoreQty] - A.[ResvStQty]) - A.[ResvOccupyStQty]) -  case  when 
((((A.[IsProdCancel] = 1) or (A.[MO_EntityID] != 0)) or A.[ProductDate] is not null) or (A.[WP_EntityID] != 0)) 
then A.[StoreQty] else convert(decimal(24,9),0) end )) as [CanUseQty],A.Wh
from  InvTrans_WhQoh as A  
left join [CBO_ItemMaster] as A2 on (A.[ItemInfo_ItemID] = A2.[ID])  
where  (((A2.[Name] is not null and (A2.[Name] != '')))) 
and A2.Code = '{ItemCode}' AND A.Wh = {WhID} AND A2.Org = {OrgID}
group by A.ItemInfo_ItemID, 
isnull( case  when A2.[ItemFormAttribute] in (16, 22) then A.[ItemInfo_ItemName] else A2.[Name] end ,''),A.[Wh]";
            var dt = DbHelperSQL.Query(sql);
            decimal whQty = 0;
            var rows = dt.Tables[0].Rows;
            if (rows.Count > 0)
            {
                whQty = Convert.ToDecimal(rows[0]["CanUseQty"]);
            }
            return whQty;
        }

        /// <summary>
        /// 条码记录在库检查
        /// </summary>
        /// <param name="OrgID"></param>
        /// <param name="barCodes"></param>
        /// <returns></returns>
        private List<string> BarCodeBECheck(long OrgID, List<string> barCodes)
        {
            string qrySql = $@"select Code from Cust_BarCodeBE where Org = {OrgID} and Code in ({string.Join(",", barCodes.Select(t => $"'{t}'"))})";
            DataSet barCodeCheckDS = DbHelperSQL.Query(qrySql);
            List<string> codes = new List<string>();
            if (barCodeCheckDS.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in barCodeCheckDS.Tables[0].Rows)
                {
                    codes.Add(row["Code"].ToString());
                }
            }
            return codes;
        }

        public string xmlPara([FromBody] EDIRcvDto para)
        {
            return "";
        }

        [HttpGet]
        public string idNameValue(string orgID)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($@"select 
isnull( case  when A2.[ItemFormAttribute] in (16, 22) then A.[ItemInfo_ItemName] else A2.[Name] end ,'') as [ItemSeg_Name], 
A2.Code,
sum((((A.[StoreQty] - A.[ResvStQty]) - A.[ResvOccupyStQty]) -  case  when 
((((A.[IsProdCancel] = 1) or (A.[MO_EntityID] != 0)) or A.[ProductDate] is not null) or (A.[WP_EntityID] != 0)) 
then A.[StoreQty] else convert(decimal(24,9),0) end )) as [CanUseQty],wh.Name
from  InvTrans_WhQoh as A  
left join [CBO_ItemMaster] as A2 on (A.[ItemInfo_ItemID] = A2.[ID])  
left join CBO_Wh_Trl wh on A.Wh= wh.id and wh.SysMLFlag = 'zh-CN'
where  (((A2.[Name] is not null and (A2.[Name] != '')))) ");
            if (!string.IsNullOrEmpty(orgID) && orgID != "0")
            {
                sb.AppendLine($@"and A2.Org = {orgID}");
            }
            sb.AppendLine($@"group by A.ItemInfo_ItemID, 
isnull( case  when A2.[ItemFormAttribute] in (16, 22) then A.[ItemInfo_ItemName] else A2.[Name] end ,''),wh.Name,A2.Code");
            var dt = DbHelperSQL.Query(sb.ToString());
            return JsonConvert.SerializeObject(dt.Tables[0]);
        }

        #region DTOs
        //public class Result<T>
        //{

        //	public int code { get; set; } = 1;


        //	public T data { get; set; }

        //	public string msg { get; set; } = "";
        //}
        public class Warehouse
        {
            public Int64 id { get; set; }
            public string Name { get; set; }
            public string Code { get; set; }
        }
        public class Organization
        {
            public Int64 ID { get; set; }
            public string Name { get; set; }
            public string Code { get; set; }
        }
        public class PullListRTNDTO
        {
            public string warehouse { get; set; }
            public string warehouseId { get; set; }
            public List<PullListDTO> PullLists { get; set; }
        }

        public class ASNRTNDTO
        {
            public Int64 asnId { get; set; }
            public string supplierName { get; set; }
            public string supplierId { get; set; }

            public List<ASNDTO> detailList { get; set; }
        }

        public class PullListReciveDTO
        {
            public long org { get; set; }
            public long userId { get; set; }
            public string userName { get; set; }
            public string Warehouse { get; set; }
            public string TargetWarehouse { get; set; }
            public List<string> list { get; set; }
        }

        public class ASNLineListReciveDTO : ContextPara
        {
            public long org { get; set; }
            public long asnId { get; set; }
            public string asnDocNo { get; set; }
            public long userId { get; set; }
            public string userName { get; set; }
            public List<string> list { get; set; }
        }

        public class PullListInfoDTO
        {
            public string pulllistcode { get; set; }
            public long org { get; set; }
            public string user { get; set; }
        }

        public class ASNInfoDTO
        {
            public string ASNCode { get; set; }
            public long org { get; set; }
            public string user { get; set; }
        }

        public class BarCodeDTO
        {
            public Int64 orgid { get; set; }
            public string itemmastercode { get; set; }
            public string lotmastercode { get; set; }
            public string suppliercode { get; set; }
            public decimal Qty { get; set; }
            public string Receivement { get; set; }
            public string SerialNum { get; set; }
        }
        public class BarCodeInfo
        {
            public Int64 ItemMaster { get; set; }
            public string ItemMasterName { get; set; }
            public Int64 LotMaster { get; set; }
            public string LotMasterCode { get; set; }
            public Int64 Supplier { get; set; }
            public string SupplierName { get; set; }
            public decimal Qty { get; set; }
            public string Receivement { get; set; }
            public string SerialNum { get; set; }
            public string BarCodeID { get; set; }
        }
        public class PullListDTO
        {
            public bool State { get; set; } = false;
            public Int64 PullList { get; set; }
            public Int64 PullListDemandLine { get; set; }
            public Int64 ItemMaster { get; set; }
            public string ItemMasterName { get; set; }
            public string ItemMasterCode { get; set; }
            public decimal RequireQty { get; set; }
            public decimal Qty { get; set; } = 0;
            public decimal TotalIssuedQty { get; set; }
            public Int64 LotMaster { get; set; } = 0;
            public string LotMasterCode { get; set; } = "";
            public Int64 Supplier { get; set; } = 0;
            public string SupplierName { get; set; } = "";

            public string UsedBarCode { get; set; }

        }


        public class ASNDTO
        {

            public Int64 ASNID { get; set; }
            public string ASNDocNo { get; set; }
            public Int64 asnlineid { get; set; }
            public string purchaseorder { get; set; }
            public string asnLineno { get; set; }
            public Int64 ItemMaster { get; set; }
            public string itemCode { get; set; }
            public string itemName { get; set; }
            public decimal arrivalQty { get; set; }
            public decimal qualifiyQty { get; set; }
            public decimal unqualifiyQty { get; set; } = 0;
            public string whcode { get; set; }
            public string wh { get; set; }
            public string bincode { get; set; }
            public string bin { get; set; }
            public decimal ConcessionQty { get; set; } = 0;
            public string RcvExceptions { get; set; }

        }

        public class ReciveData
        {
            public long factoryId { get; set; }
            public string userNo { get; set; }
            public string workcenterId { get; set; }
            public string userToken { get; set; }
            public string accountSets { get; set; }
            public string dtoJsonStr { get; set; }
            public string code { get; set; }
        }
        public class LoginDto
        {
            public string UserNo { get; set; }
            public string UserPwd { get; set; }

        }
        public class LoginInfo
        {
            public string username { get; set; }
            public long factoryId { get; set; }
            public string password { get; set; }
            public long userId { get; set; }
        }


        public class InventoryListLineInfoDTO
        {
            public string InventoryListDocNo { get; set; }
            public string InventoryListLineNo { get; set; }
            public string ItemMasterCode { get; set; }
            public long org { get; set; }
            public string user { get; set; }
        }
        public class InventoryListLineRTNDTO
        {
            public long InventoryListLineID { get; set; }
            public long InventorySheetLineID { get; set; }
            public string ItemMasterName { get; set; }
            public string ItemMasterCode { get; set; }
            public decimal Qty { get; set; }
            public string WHName { get; set; }
            public List<InventoryListLineDetailDto> detailList { get; set; }
        }
        public class InventoryListLineDTO
        {

            public string userCode { get; set; }
            public string OrgCode { get; set; }
            public long OrgID { get; set; }
            public long InventorySheetLineID { get; set; }
            public long InventoryListLineID { get; set; }
            public decimal InventoryListLineQty { get; set; }
            public List<string> list { get; set; }
        }

        public class InventoryListLineDetailDto
        {
            public string ItemMasterName { get; set; }
            public string ItemMasterCode { get; set; }
            public int IsCreate { get; set; } = 0;
            public string BarCode { get; set; }
            public decimal Qty { get; set; }
            public int LineNum { get; set; }
        }

        public class SetASNDto
        {

            public string userCode { get; set; }
            public string OrgCode { get; set; }
            public string Ycarrivecode { get; set; }
            public string SupplierCode { get; set; }
            public DateTime ShipDate { get; set; }

            public List<SetASNLineDto> list { get; set; }
        }

        public class SetASNLineDto
        {

            public int DocLineNo { get; set; }
            public string ItemCode { get; set; }
            public DateTime PlanArriveDate { get; set; }
            public string PurchaseOrder { get; set; }
            public string POLineNo { get; set; }
            public decimal ShipQtyTU { get; set; }
            public string LotCode { get; set; }
            public string PackagesNum { get; set; }
            public string PackagesCodes { get; set; }
        }
        #endregion


        /// <summary> 
        /// MD5 加密字符串 
        /// </summary> 
        /// <param name="rawPass">源字符串</param> 
        /// <returns>加密后字符串</returns> 
        private static string MD5Encoding(string rawPass)
        {
            // 创建MD5类的默认实例：MD5CryptoServiceProvider 
            MD5 md5 = MD5.Create();
            byte[] bs = Encoding.UTF8.GetBytes(rawPass);
            byte[] hs = md5.ComputeHash(bs);
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hs)
            {
                // 以十六进制格式格式化 
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }

        /// <summary> 
        /// MD5盐值加密 
        /// </summary> 
        /// <param name="rawPass">源字符串</param> 
        /// <param name="salt">盐值</param> 
        /// <returns>加密后字符串</returns> 
        public static string MD5Encoding(string rawPass, object salt)
        {
            if (salt == null) return rawPass;
            return MD5Encoding(rawPass + "{" + salt.ToString() + "}");
        }

        //[HttpPost]
        //public Result<string> CreateCompleteRptSV(string data, string JobId)
        //{
        //	CreateCompleteRptSV createCompleteRptSV = new CreateCompleteRptSV();
        //	createCompleteRptSV.JobMsg = data;
        //	var bak = createCompleteRptSV.Do();
        //	Result<string> rtn = new Result<string>();
        //	if (bak != "")
        //	{
        //		string UPDJson = JsonConvert.SerializeObject(new QuartzTaskInfoUPDDTO
        //		{
        //			factoryId = "",
        //			userNo = "",
        //			workcenterId = "",
        //			userToken = "",
        //			accountSets = "",
        //			dtoJsonStr = "",
        //			quartzTaskInfoDTO = new QuartzTaskInfoDTO
        //			{
        //				jobId = JobId,
        //				jobResult = bak,
        //				quartzStatus = 1
        //			},
        //			quartzTaskLogInfoDto = new List<QuartzTaskLogInfoDto>() { new QuartzTaskLogInfoDto {
        //				jobId = JobId,
        //				taskDate = Convert.ToString(DateTime.Now)
        //			} },
        //		});
        //		var UPDrtn = HttpPosts("http://192.168.1.16:5002/api/app/default-quartz-task/quartz-task-info-upd", UPDJson);


        //		rtn.msg = bak;
        //		rtn.code = 0;
        //	}
        //	return rtn;
        //}

        public static long GuidToLongID()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

        /// <summary>
        /// DES数据加密
        /// </summary>
        /// <param name="targetValue">目标值</param>
        /// <param name="key">密钥</param>
        /// <returns>加密值</returns>
        [HttpGet]
        public string Encrypt(string targetValue, string key)
        {
            if (string.IsNullOrEmpty(targetValue))
            {
                return string.Empty;
            }

            var returnValue = new StringBuilder();
            var des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(targetValue);
            // 通过两次哈希密码设置对称算法的初始化向量   
            des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                                                    (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").
                                                        Substring(0, 8), "sha1").Substring(0, 8));
            // 通过两次哈希密码设置算法的机密密钥   
            des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                                                    (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")
                                                        .Substring(0, 8), "md5").Substring(0, 8));
            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            foreach (byte b in ms.ToArray())
            {
                returnValue.AppendFormat("{0:X2}", b);
            }
            return returnValue.ToString();
        }

        /// <summary>
        /// DES数据解密
        /// </summary>
        /// <param name="targetValue"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Decrypt(string targetValue, string key)
        {
            if (string.IsNullOrEmpty(targetValue))
            {
                return string.Empty;
            }
            // 定义DES加密对象
            var des = new DESCryptoServiceProvider();
            int len = targetValue.Length / 2;
            var inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(targetValue.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            // 通过两次哈希密码设置对称算法的初始化向量   
            des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                                                    (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").
                                                        Substring(0, 8), "sha1").Substring(0, 8));
            // 通过两次哈希密码设置算法的机密密钥   
            des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                                                    (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")
                                                        .Substring(0, 8), "md5").Substring(0, 8));
            // 定义内存流
            var ms = new MemoryStream();
            // 定义加密流
            var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }


        [HttpGet]
        public string GetIP()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    //Console.WriteLine("IP Address = " + ip.ToString());
                    return ip.ToString();

                }
            }
            return "未找到";

        }

    }
}
